Things I should have known about Python #1

After the whirlwind that was Pycon 2011, I’ve started trying to learn as much as I can about Python.  I’ve even stumbled upon the Python subreddit gem.  I was reading this which pointed me to this, and came across a few things (of the many out there) I didn’t yet know:

  1. In the interactive interpreter there is a hidden temporary variable “_”.  It holds onto the last printed value that was not None.  Oh Python, why are you so sneaky?
  2. Dictionaries have a setdefault() method that allows you to bypass existence checks for keys and simply (get) or (set and get) in one go.  Fascinating.  SO MANY THINGS I NEED TO LEARN THAT ARE SO BASIC!!
  3. You can define the trueness of a user-defined class by overriding the built-in __len__ or __nonzero__ methods, with __len__ being preferred if your class is a container with a natural length.  Fascinating.  I want to find a reason to use this.  However, all of our classes are really just functional, and all of our data is JSON, so trueness is built-in.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>