Sitemap
Tuan le Van

Tuan le Van

Better coding in Python

1 min readOct 14, 2020

--

Here is some tips and tricks for writing better code in Python

Tuple

tuple unpacking

parallel assignment of tuple in python is readable and flexible

using dummy variable

grab excess items

nested tuple unpacking

Named tuples

collection.namedtuple is factory function for creating tuple subclasses with named fields. The instance take exactly the same amount of memory as tuple. Named tuple assign are readable and self-documenting code.

We can be more explicit with NamedTuple (python3)

String Manipulation

remove some leading and trailing characters

separate string

align string

Item and Attribute Accessing

get value for a key in dictionnary

clean code with slice objects

clean code with itemgetter

clean code with attrgetter

Dictionnary

use defaultdict

get indexes of all occurrences of character in a string

maintain insertion order

from python3.6, the standard dict maintains insertion order. For previous version, we can use OrderedDict.

remove duplicates from a list while preserving order (in py2 and py3)

Function

use function as object

function instead of class

sometimes, instead of defining and instantiating classes, you can simply use functions.

nonlocal declaration was introduced in python 3 to make a function inside a function, which uses the variable as a non local variable

Most of the tricks and tips i have learned from Fluent Python by Luciano Ramalho and from my current job.

Get Tuan le Van’s stories in your inbox

Join Medium for free to get updates from this writer.

Thank you for reading and I hope you found this article helpul!

If you have any suggestions please don’t hesitate to comment. 😊

--

--