The Zen of Python

»> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one— and preferably only one —obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

See the Python Style Guide PEP8

Posted March 03, 2012 | 3243 Comments

Python Pitfalls #1

Refreshing my Python, I looked up some common pitfalls.

More links at the end

definition

Immutable objects are numbers and strings, while mutable objects include lists and tuples.

class attributes are shared for mutable objects

to wit:

    >>> class Foo:
    ...     i = 0
    ...     l = []
    ... 
    >>> f = Foo()
    >>> g = Foo()
    >>> f.i = 100
    >>> g.l.append(100)
    >>> f.i, g.i
    (100, 0)
    >>> f.l, g.l
    ([100], [100])

appending the mutable class attribute affects all instances. it’s best to initialize our objects to new instances, like so:

    >>> class Foo:
    ...     l = []
    ...     def __init__(self):
    ...             self.l = []     # set l to a new object
    ... 
    >>> f = Foo()
    >>> g = Foo()
    >>> f.l.append(123)
    >>> g.l.append(456)
    >>> f.l, g.l
    ([123], [456])

 

mutable default arguments

consider:

    >>> def bar(x=[]):
    ...     x.append(4)
    ...     print x
    ... 
    >>> bar()
    [4]
    >>> bar()
    [4, 4]
    >>> bar()
    [4, 4, 4]

that was unexpected, but makes this very clear: mutable default arguments are bound once, when the function is created, not when it is called.

this behaviour will change any lists you pass to that same argument:

    >>> x = [1, 2, 3]
    >>> bar(x)
    [1, 2, 3, 4]
    >>> x               # our object was modified
    [1, 2, 3, 4]

this can be useful if kept in mind, where multiple objects need modifications returned by a function.

float point rounding errors

Because of the way machines store floating digits, consider this:

    >>> 0.1
    0.10000000000000001
    >>> str(0.1)
    '0.1'
    >>> repr(0.1)
    '0.10000000000000001'


Question: What best approach do we take when performing comparisons on floats?
Answer: Use Decimal where strict equality invariants is needed.

    >>> from decimal import *
    >>> 0.1
    0.10000000000000001
    >>> Decimal('0.1')
    Decimal('0.1')

More on Decimals at the Python docs page

Multiple Exception Handling

 

    >>> try:
    ...     1/0
    ... except ZeroDivisionError, e:
    ...     print e

Will place the exception instance in e (the optional name of our exception object). Place multiple handlers in a tuple to cover many errors:

    try:
        ...something that raises an error...
    except (IndexError, ValueError):
        # does catch IndexError and ValueError

 

Links

Posted February 24, 2012 | 8 Comments

Mouseless Mondays

Can you live without your mouse for a day? It takes a lot of patience and learning, that’s for sure! Here are some alternatives I use:

  • Use a tiling Window Manager, or turn your current WM into one with Pytyle
  • Make shortcuts for desktop switching, window managing and music control
  • Simulate mouse clicks and drags with your keyboard and keynav
  • Hide the mouse under your desk slash plug it out

Motivations for doing this?

  • Trackpads frustrate me
  • Because I can, and
  • I’m a little crazy
Posted February 13, 2012 | 0 Comments

Chyrp Blog Engine

We moved to a new blog engine: Chyrp. I found Wordpress a bit bloated on low-speed wireless, plus I like the minimalism of it.

Lest we forget that Blogs started as online Development Logs, text and links, it reminds us that information was the motive. Everyone likes flashy, sometimes indistinguishable from cruft, which divides usability from frustration.

When you step back to the basics, once again you think in terms of: “How else can I do this?”.

Aah, so refreshing!

Posted February 11, 2012 | 2 Comments

Crunchbang Linux, minimal and mouseless

Who can use these laptop and netbook touchpads, trackpads, whatever you call the thing you-accidentally-tap and lose-focus-and-type-into-the-wrong-spot.

Specialized layout keyboard navigation is the way to go!

  • Customized Conky to a top horizontal bar, always visible by setting my desktop margins.
  • Installed Pytyle to organize my windows running on top of Openbox, with vi-like keybindings relying on the Super key.
  • Hacked in a few global shortcuts for easy volume management and frequently used applications.


 
Crash course in navigation

So far I can manage 99% of tasks using the keyboard layout I set out below.

The Super is also known as the Winkey

Window shortcuts

  • cycle the focused window, Super-J/K
  • move the active window between panels on the screen, Super-Ctrl-J/K
  • move the active windows to another desktop, Super-Shift-J/K
  • switch desktops, Super-Alt-J/K
  • Change master tile size, Super-H/L
  • Add/remove master tiles, Super-./,

Media shortcuts

  • Ctrl-Ins, up volume
  • Ctrl-Del, down volume
  • Ctrl-Backspace, pause/play music
  • Super-V, alsa volume mixer
  • Super-M, mocp music player

CLI Mode

When it comes to flash in websites that steals your focus, I feel like screaming. Due to bandwidth limits I use the text-mode CLI browser Elinks, and the CLI mail client Alpine.

I rebound many Elinks shortcuts for a vi-like experience to scrolling the page, within the page, browsing history, selecting links and so forth.

Posted November 09, 2011 | 1 Comment
    Next →