An A-Z of useful Python tricks

This prints out complex structured objects in an easy-to-read format.A must-have for any Python developer who works with non-trivial data structures.import requestsimport pprinturl = ''users = requests.get(url).json()pprint.pprint(users)QueuePython supports multithreading, and this is facilitated by the Standard Library’s Queue module.This module lets you implement queue data structures..These are data structures that let you add and retrieve entries according to a specific rule.‘First in, first out’ (or FIFO) queues let you retrieve objects in the order they were added..‘Last in, first out’ (LIFO) queues let you access the most recently added objects first.Finally, priority queues let you retrieve objects according to the order in which they are sorted.Here’s an example of how to use queues for multithreaded programming in Python.__repr__When defining a class or an object in Python, it is useful to provide an ‘official’ way of representing that object as a string..For example:>>> file = open('file.txt', 'r')>>> print(file)<open file 'file.txt', mode 'r' at 0x10d30aaf0>This makes debugging code a lot easier..Add it to your class definitions as below:class someClass: def __repr__(self): return "<some description here>"someInstance = someClass()# prints <some description here>print(someInstance)shPython makes a great scripting language..Sometimes using the standard os and subprocess libraries can be a bit of a headache.The sh library provides a neat alternative.It lets you call any program as if it were an ordinary function — useful for automating workflows and tasks, all from within Python.import shsh.pwd()sh.mkdir('new_folder')sh.touch('new_file.txt')sh.whoami()sh.echo('This is great!')Type hintsPython is a dynamically-typed language..You don’t need to specify datatypes when you define variables, functions, classes etc.This allows for rapid development times..However, there are few things more annoying than a runtime error caused by a simple typing issue.Since Python 3.5, you have the option to provide type hints when defining functions.def addTwo(x : Int) -> Int: return x + 2You can also define type aliases:from typing import ListVector = List[float]Matrix = List[Vector]def addMatrix(a : Matrix, b : Matrix) -> Matrix: result = [] for i,row in enumerate(a): result_row =[] for j, col in enumerate(row): result_row += [a[i][j] + b[i][j]] result += [result_row] return resultx = [[1.0, 0.0], [0.0, 1.0]]y = [[2.0, 1.0], [0.0, -2.0]]z = addMatrix(x, y)Although not compulsory, type annotations can make your code easier to understand.They also allow you to use type checking tools to catch those stray TypeErrors before runtime..Probably worthwhile if you are working on large, complex projects!uuidA quick and easy way to generate Universally Unique IDs (or ‘UUIDs’) is through the Python Standard Library’s uuid module.import uuiduser_id = uuid.uuid4()print(user_id)This creates a randomized 128-bit number that will almost certainly be unique.In fact, there are over 2¹²² possible UUIDs that can be generated..That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).The probability of finding duplicates in a given set is extremely low..Even with a trillion UUIDs, the probability of a duplicate existing is much, much less than one-in-a-billion.Pretty good for two lines of code.Virtual environmentsThis is probably my favorite Python thing of all.Chances are you are working on multiple Python projects at any one time..Unfortunately, sometimes two projects will rely on different versions of the same dependency.. More details

Leave a Reply