Perspective Unspoken

My perspective on Git, Docker, Python, Django, PHP and other stuff

2 Python features I wish I knew from the get go

As developers we’re always learning and improving. New API’s come out, new versions of libraries come out, and we’re forever stuck expanding our minds, shifting paradigms and adopting new approaches. Ever so often though, we’ll find that we’re using a tool, as a daily driver even and we discover there are some features we just never came across. Features that could have made our code shorter and our life alot easier. *sigh* If we only knew.

I often have made it a habit that when I’m learning a new language or API or whatever… after getting past the basics I tend to search for “optimization” and “advanced” topics so I start to see how “real” coders use the tool. That search often reveals that many of the basics are inefficient and merely flirt material to woo you in. Beyond the basics is where you really start to use a tool properly.

Pretty much the same happened to me with Python and Django. I’ve written quite alot of code in Python over the last couple of years and man I wish I’d been using these features more.

Named Tuples

A beautiful feature of Python, that allows you to use tuple notation to make what looks and feels like a normal object, without having to define a class.

What Python actually does is create a class that’s a subclass of the Python tuple and adds properties for each of the fields you provided. If you want to look at the implementation, you can pass verbose=True to the namedtuple function.

There are so many times you want to return more than one thing from a function but defining an entire class is overkill. Named tuples come in very handy here, especially when you often are returning the same outputs over different functions.

There are also many times that you need to iterate over a list of tuples for some reason. Named tuples come in here as a great replacement as well. I did a post about why using values_list is better, you can check that out.

Though this is a simple example, there are times when what you’re trying to juggle gets a little wider and more complex and it helps to be able reference the items in your tuple by name. It really helps when you’re trying to read over your code months later as it promotes healthy code re-use. If you’re able to capture patterns you’re always using, named tuple will help annotate the code you write much better.

Finally, as one last plus of named tuples, they can easily be converted to a dictionary.

An Ordered Dictionary to be specific.


Magic Methods

Sure we’ve seen the double underscore methods all over the place. Most of us have used __init__ and __new__ methods, but there are countless others that I wish I had been using ages ago. Using these magic methods help keep the objects you define close to the zen of Python and keep you from writing unnecessary code. I’ve written quite a few “Manager” type objects that have to keep track of some other objects and properties on those objects. I’ve seen quite a few cases where I should have replaced some of my code with magic methods.

To illustrate my point, I’ll use a class called ReportManager that is responsible for keeping track of several Report instances. So let’s imagine this basic structure…

__iter__ method

Firstly, let’s start with getting a list of reports. Typically, I’d end up writing a method to return the list of reports. However, the __iter__ is actually a nice replacement.

And now with __iter__.

__iter__ is great for providing an iterable object that you can iterate over. It’s a pattern you see used all over in different projects. So no need to go write a method to return a list, just implement __iter__.


__len__ method

Another very typical use case. I need to return a count of how many reports I have in the Report Manager. Again, I’d write a method specifically to address that.

Instead though, the __len__ method can be used to describe the length of the object.


__getitem__ methods

The __getitem__ method is called when objects are accessed like self[key]. We can use this to provide us with string and integer based indexing of our reports. Here’s how.

So we use __getitem__ for report name lookups (string) and if we get an integer, then we do an index based lookup. This allows us to be able to do the following:


__contains__ method

This is yet another method that I’ve implemented alternatively countless times. Usually I’d write a has_report method that returns True or False. This method was written just for that.

Like I said though, there are countless others. There are functions for construction of objects, controlling how equality works, making or faking a sequence, context managers, copying, pickling,  Rafe Kettler does a good job providing a summary of all of them here. Or you can look at this shortened Appendix on his blog.





jaywhy13 • January 4, 2016

Previous Post

Next Post