Live and Learn

I stumbled upon Ted Dziuba's blog today and found this gem: "Independent object cycles where one of the objects has a __del__ method don't get garbage collected." I didn't know that.

I didn't know Gunnery Sergeant Hartman knew Python either... Live and learn :)

Continue reading
258 Hits

Decorators, Shmecorators

This is how I learned to write decorators:

class Decorator:
  def __init__(self, func):
    self.func = func

  def __call__(self, *args):
    # do stuff
    return self.func(*args)

But today I was reminded of the classic way of writing decorators:

def mydecorator(func):
  def mydecorator_guts(*args, **kwargs):
    # do stuff
    return func(*args, **kwargs)
  return mydecorator_guts

Simpler and more to the point. And NO CLASSES. This ain't Java :)

Continue reading
250 Hits

Return last item if duplicates exist

I have a "for item in collection:" loop, as classic as it could be. The collection is sorted, there are duplicates. I need to return the last item if duplicate values exist.

It took me 15 minutes to arrive at for item in reversed(collection): solution. That is some slow thinking! Just when I needed to think fast. Sigh.

Continue reading
254 Hits

*args and **kwargs

I thought after using Python for 6 years now there will be no unknown territories for me. I thought I mastered the language. Phew. Far from it.

So, for starters, I learned about *args and **kwargs. I had no idea those exist and not once, not twice but many times over I was passing arguments to a function via a list or dictionary. I can still pass them as a list or dictionary but with that syntax it would be more organized and clean.

Continue reading
228 Hits
Go to top