SoFunction
Updated on 2024-11-20

Summarize three common tricks in Python programming

You can see some common tricks in python code, so here's a quick summary.
json string formatting

In the development of web applications often use json strings, but a long json string is less readable, it is not easy to see the structure of the string. In this case, you can use python to print out the json string beautifully.

root@Exp-1:/tmp# cat  
{"menu": {"breakfast": {"English Muffin": {"price": 7.5}, "Bread Basket": {"price": 20, "desc": "Assortment of fresh baked fruit breads and muffins"}, "Fruit Breads": {"price": 8}}, "drink": {"Hot Tea": {"price": 5}, "Juice": {"price": 10, "type": ["apple", "watermelon", "orange"]}}}}
root@Exp-1:/tmp# 
root@Exp-1:/tmp# cat  | python -m 
{
  "menu": {
    "breakfast": {
      "Bread Basket": {
        "desc": "Assortment of fresh baked fruit breads and muffins",
        "price": 20
      },
      "English Muffin": {
        "price": 7.5
      },
      "Fruit Breads": {
        "price": 8
      }
    },
    "drink": {
      "Hot Tea": {
        "price": 5
      },
      "Juice": {
        "price": 10,
        "type": [
          "apple",
          "watermelon",
          "orange"
        ]
      }
    }
  }
}
root@Exp-1:/tmp# 

The beauty of else

In some scenarios we need to determine if we are jumping out of a for loop with a break, and only handle the break jumps accordingly. The usual way to do this is to use a flag variable to identify if we're jumping out of a for loop. For example, we can see if there is a multiple of 17 between 60 and 80 in the following example.

flag = False
for item in xrange(60, 80):
  if item % 17 == 0:
    flag = True
    break

if flag:
  print "Exists at least one number can be divided by 17"

In fact, you can use else to achieve the same effect without introducing a new variable.

for item in xrange(60, 80):
  if item % 17 == 0:
    flag = True
    break
else:
  print "exist"

setdefault method

A dictionary is a powerful built-in data structure in python, but there are some inconvenient ways to use it, such as when nested in multiple levels.

dyna_routes = {}
method = 'GET'
whole_rule = None
# Some other logical processing
...
if method in dyna_routes:
  dyna_routes[method].append(whole_rule)
else:
  dyna_routes[method] = [whole_rule]

There's actually a simpler way to write this that achieves the same effect

self.dyna_routes.setdefault(method, []).append(whole_rule)

Alternatively, you can use the module

import collections
dyna_routes = (list)
...
dyna_routes[method].append(whole_rule)