How to use your self
There are a lot of questions on StackOverflow asking "what's the deal with self?"
Many of them are asking a language-design question: Why does Python require explicit self when other languages like C++ and friends (including Java), JavaScript, etc.
Tkinter validation
Tkinter makes slapping together a simple GUI very easy. But unfortunately, many of its features aren't very well documented.
7What's the deal with ttk.Frame.__init__(self, parent)
In Python 2.x Tkinter code, you see a lot of stuff like this:
class MyFrame(Frame): def __init__(self, parent, n): Frame.__init__(self, parent) self.n = n Why?
Inheritance and overriding
Some people start on Tkinter before getting far enough into learning Python.
Does Python pass by value, or by reference?
Does Python pass by value, or pass by reference?
Neither.
If you twist around how you interpret the terms, you can call it either. Java calls the same evaluation strategy "pass by value", while Ruby calls it "pass by reference".
"if not exists" definitions
In database apps, you often want to create tables, views, and indices only if they don't already exist, so they do the setup work the first time, but don't blow away all of your data every subsequent time. So SQL has a special "IF NOT EXISTS" clause you can add to the various CREATE statements.
November 7th, 2013
Sometimes you want to write a round-trippable __repr__ method--that is, you want the string representation to be valid Python code that generates an equivalent object to the one you started with.
First, ask yourself whether you really want this.
repr + eval = bad idea
Many novices notice that, for many types, repr and eval are perfect opposites, and assume that this is a great way to serialize their data:
def save(path, *things): with open(path, 'w') as f: for thing in things: f.write(repr(thing) + '\n') def load(path): with open(path) as f: return [eval(line) f
Solving callbacks for Python GUIs
There are a number of blogs out there that tackle the problems of callbacks for servers, or for Javascript, but novices trying to write Python GUIs shouldn't have to learn about the different issues involved in servers, or a whole different language.
Using python.org binary installations with Xcode 5
So you've installed Python from an official binary installer on python.org's Releases page, you've installed Xcode from the App Store and the Command Line Tools from Xcode, you've installed pip from its setup script.
defaultdict vs. setdefault
Stack Overflow is full of questions where the answer is to create a "multidict", a dict mapping each key to a list of values.
There are two ways to do this, using defaultdict, or using a regular dict with setdefault.
Lazy restartable iteration
The problem
Often, using an iterator lazily is better than generating a sequence (like the one you get from a list comprehension).
Arguments and parameters
A lot of people—not just novices—mix up parameters and arguments, especially when it comes to things like how default-valued parameters and keyword arguments, or argument unpacking and variable parameters.
3How grouper works
How grouper works
A very common question on StackOverflow is: "How do I split a sequence into evenly-sized chunks?"
If it's actually a sequence, rather than an arbitrary iterable, you can do this with slicing.
Comprehensions vs. map
This question comes up over and over and over on Stack Overflow—even if it's not the main question itself (as in those examples), it's often a side argument in the comments.
2Basic thread pools
Let's say you have a network server built around a single-threaded event loop—gevent, Twisted, asyncore, something simple you built on top of select.select, whatever. It's important to handle every event quickly.
Sorted collections in the stdlib
People want sorted collections in the stdlib, but no one has ever made a solid proposal to add them.
4Mac environment variables
You're writing a GUI app using Tkinter or PySide or your favorite GUI library, and testing it in-place, everything works.
Then you build a .app bundle out of it, double-click it in Finder, and it can't read your environment variables.
Syntactic takewhile?
There's a pair of intertwined threads in python-ideas about coming up with a way to break out of list comprehensions and generator expressions early.
Oscar Benjamin gives a good example:
isprime = all(n % p for p in takewhile(lambda p: p**2 < n, primes_seen))
That's ugly.
Can you optimize list(genexp)
What's the difference between a list comprehension, and calling list on a generator expression? (By the way, everything below applies to set comprehensions and, with trivial tweaks, dict comprehensions, but I'm only going to talk about lists for simplicity.)
To be concrete, what's the difference be
MISRA-C and Python
Recently, there have been a few proposals to change Python's syntax to make it easier to avoid break and continue statements.
The reasoning seems to be that many people are taught never to use break and continue, or to only have a single break in any loop.
How to split your program in two
Sometimes, you need to split a program into two parts.
How methods work
Look at this familiar code:
class Foo(object): def __init__(self, a): self.a = a def bar(self, b): return self.a + b foo = Foo(1)
How do __init__ and bar get that self parameter?
Unbound methods
Well, bar is just a plain old function.
readlines considered silly
Never call readlines() on a file
Calling readlines() makes your code slower, less explicit, less concise, for absolutely no benefit.
There are hundreds of questions on places like StackOverflow about the readlines method, and in every case, the answer is the same.
Comprehensions for dummies
You don't actually have to be a dummy to not get list comprehensions. Only a few languages (after Python, the next most popular is probably Haskell) support them. And they're only "easy" once you learn to think a different way.
You do eventually want to learn to think that way.
Sockets are byte streams, not message streams
The first time you try to write a network client or server directly on top of sockets, you do something like this:
for filename in filenames: with open(filename, 'rb') as f: sock.sendall(f.read())
And then, on the other side:
for i in count(0): msg = sock.recv(1<<32) if not msg: break with open('
Why you don't want to dynamically create variables
(Someone pointed out to me that Ned Batchelder has a similar post called Keep data out of your variable names.
7Why eval/exec is bad
Novices to Python often come up with code that tries to build and evaluate strings, like this:
for name in names: exec('{} = {}'.format(name, 0))
… or this:
exec('def func(x): return {} * x**2 + {} * x + {}'.format(a, b, c)) return func
99% of the time, this is a problem you shouldn't be solving
Iterator Pipelines
If you look at the major changes in Python 3, other than the Unicode stuff, most of them are about replacing list-based code with iterator-based code.
2Why are non-mutating algorithms simpler to write in Python?
Let's say you've got the list [-10, 3, -2, 14, 5], and you want the list filtered to just the non-negative values.
2Sticking with Apple's Python 2.7
Why install a third-party Python 2.7?
Python.org, Homebrew, scipy.org, 69105 different blog posts explaining how to install numpy/scipy/etc. on a Mac, etc. all tell you to install a different Python alongside Apple's.
Installing scipy, etc. for Python 3 on Mac
tl;dr
Install Xcode from the App Store, then install the Command Line Tools from Xcode (Preferences | Downloads | Components). Install Python 3.3.0 (or the latest non-beta version, if you're in the future) by running the "Mac OS X 64-bit/32-bit Installer".
Installing scipy, etc., with Apple's Python 2.7
tl;dr
Install Xcode from the App Store, then install the Command Line Tools from Xcode (Preferences | Downloads | Components).