Blog - Trusted Team Extension Partner For Europe & USA

Python-ing it better - Best Software Development Team Extension Partner for Nordics

Written by Sakib Alam | 11/01/2019

Where I work; we are obsessed with python, we use it everyday and to us python is an art. Python does not force rules unto you. But there’s always a better way of doing it; to us, a pythonic way. This article will try to show off some cool tricks and good practices in python that you can use to level up in the art of python.

Using built in functions 

Most of us start our coding career with C/C++. Which is great and all but it drills in a certain way of doing things that we carry with us throughout the year and that is “assign then modify”. Lets talk code

 

We declare an empty vector and then loop over it to populate. There’s nothing wrong with it and it works absolutely OKAY. Lets convert this to python

 

Nothing wrong here either. But… 

There’s gotta be a better, more pythonic way of doing this

 

Wow. The map function can call a given function for every element of a given iteratables. We can use this for loads of stuff like-

 

Cool right? Say we need to get all the elements with session=True. Let’s do it the boring way first!

 

Looks OKAY, gets the job done but ew, we need a pythonic way. Here’s one:

 

Wow. What if you only need the first match? Don’t you worry, don’t you worry child, python’s got a plan for you!

 

Python has a plethora of built in functions that you can use to write clean self-explained code. Please use them and LEVEL UP.

Comprehending Comprehensions

Python is an art. There are a number of ways to do what you need to do. You’re the painter, python is the brush. Move it the way you want.

Comprehensions are one off lines in python that can do many things in a more clear, comprehensible, concise way. Let’s get back to the first example from the previous section. How can we achieve the same thing with comprehension? Let’s talk code!

 

It can’t get any prettier than this ladies and gentlemen. This is the beauty of python. You can use list comprehensions with almost every data type. Need a dictionary? Well…

 

Talk about beauty. And you can do this with generators as well!

 

And with sets too!

 
Impressed? You should be.

Needle in the thread

Have you ever had to make a bunch of API calls and ended up doing it like this-

 

OKAY. But unfortunately I don’t have a tree full of time to wait for these to come in one by one. So let’s clear this up.

 

This is my reaction after seeing this

But I still don’t have time. Can you speed it up?

 

I mean

I hope this was able to demonstrate the beauty of python and how you can LEVEL UP as a developer. There are some caveats and gotchas when it comes to shortening codes so remember to use them wisely.