arrow to navigation
Order
Group
Python
14.11.2022 | 2 min

5 Python tricks from a tech lead

Here are five tricks for programming in Python and Django. If you don’t know the number 2, we promise it will change your life. :)

5 Python tricks from a tech lead - 2024 32
Table of Contents
  • 1. Swap variables
  • 2. tqdm - progress bar for console
  • 3. Multilevel dict
  • 4. Conditionally add an item to dict
  • 5. Django - update or create an object from dict

Hi, I'm Łukasz, and the following tips and tricks help me program faster and more conveniently daily.

I hope that you find them helpful regardless of your experience. 🙂

1. Swap variables

In Python, you can swap variables without using additional temporary variables.

Let’s say we have two variables, and we want to change their values:

Old way:

a = 10

b = 20

c = a

a = b

b = c

Pythonic way:

a = 10

b = 20

b, a = a, b

Thanks to this, the code is clear and short because you replace three lines with one.

2. tqdm - progress bar for console

This is an excellent bundle if you’re doing some script in a loop and want to follow the progress easily.

Old way:

for idx, x enumerate (elements):

print (idx / len (elements))

# some calculations

With tqdm:

for x in tqdm (elements):

# some calculations

tqdm calculates the time in which the loop will end based on the pace of progress so far. So it gives you an idea of ​​how fast the code you wrote is running. In addition, it’s a nice way of shortening the code.

I use tqdm daily because it gives me confidence and peace of mind.

3. Multilevel dict

If you have a multilevel dictionary, you can pull out properties from it without writing ifs.

Let’s say we have dicts with similar structure, but “point” can be empty for some of them:

a = {

“point”: {

“coords”: {

“x”: 1,

“y”: 2,

}

}

}

b = {

“point”: {

}

}

And we want to check the value of "x safely".

In JavaScript, we have syntactic sugar, and what about Python?

JS:

const x = a.point?.coords?.x

Python with ifs:

if “point” in a:

if “coords” in a[“point”]:

x = a[“point”][“coords”][“x”]

Python without ifs:

x = a.get(“point”, {}).get(“coords”, {}).get(“x”)

A simple and helpful trick that shortens and simplifies the code.

4. Conditionally add an item to dict

If you want to add conditionally some value into dict when you define it.

Old way:

user = {

"name": "Jan",

"surname": "Kowalski",

}

if condition_here:

user[“team”] = “og”

New way:

user = {

"name": "Jan",

"surname": "Kowalski",

**({"team": “og”} if condition_here else {})

}

5. Django - update or create an object from dict

Last but not least, a Django trick. Sometimes you want to create an object from a dictionary and put the data from that dictionary into a model. The standard Django code for this looks like this:

obj_data = {

"name": "name",

"x": 1,

"y": 2,

"z": 3

}

3dPoint.objects.update_or_create (

id = 1,

defaults = {** obj_data}

)

The defaults parameter allows you to search for parameters not in defaults and overwrite those in defaults. Information about this property is available in the Django documentation, but I know from experience that only some know or remember it. And it’s a handy trick to replace values ​​in an element or create one quickly.

Additionally, if you don't want to create an object and you want to replace the values ​​with the same dictionary, you can do this:

point = 3dPoint.objects.filter(id = 1).first()

if point:

point.__dict__.update(**obj_data)

As mentioned above, many people don't know they can use a __dict__ object and overwrite things with it, and this is a handy trick I used on my last web project to save time and manage the code better.

Please do not hesitate to drop me a line if you would like more of this type of advice or have any Python-related questions/

Let's jump in a call to discuss your idea!
Schedule a meeting
5 Python tricks from a tech lead - 2024 32 Read more