Skip to content

You will be hunted down for you getattr tricks!!!

April 30, 2014

I recently inherited a codebase with… issues. One of my favorite pastimes for improving a codebase is to scroll through log files and fix bugs. Today, I found this error:

  File ".../my_module.py", line 1337, in foo_method
    bar = foo.title,
AttributeError: 'Foo' object has no attribute 'title'

No worries, grep -r will save me! Or wait… it won’t. Because someone wrote this code:

def call_obliquely(self, method_name, args):
  return getattr(self, 'method_'+method_name)(args)

Please don’t write that. Someday, someone somewhere is going to need to refactor that function somehow. If they can’t find where you call that function, they can’t take your usage into account. Using the full name is slightly better, because at least grep -r will find it. However, our IDE using brethren will be unable to use their automated refactoring tools to rename the function, and really, all their silly mouse-clicks have to be for something.

Advertisements

From → Python tricks

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: