15 useful Python tips

Hello, everyone, I'm a programmer sophomore~

Here, I will briefly introduce 15 practical Python skills that are easy to use. If you are interested in one or more of them, you can have a look. I hope it can be helpful to you.

01 all or any

One of the many reasons why Python is so popular is that it has good readability and expressiveness.

People often joke that Python is executable pseudocode. When you can write code like this, it's hard to refute.

x = [True, True, False]
if any(x):
    print("At least one True")
if all(x):
    print("All True")
if any(x) and not all(x):
    print("At least one True And one False")

02 dir

Have you ever thought about how to look inside a Python object and what properties it has? On the command line, enter:

`dir()
dir("Hello World")
dir(dir)`

This can be a very useful feature when running Python interactively and dynamically exploring the objects and modules you are using. Read more about functions here.

03 list derivation

One of my favorite things about Python programming is its list derivation.

These expressions can easily write very smooth code, almost like natural language.

numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]
cities = ['London', 'Dublin', 'Oslo']

def visit(city):
    print("Welcome to "+city)
    
for city in cities:
    visit(city)

04 pprint

Python's default print function does its job. However, if you try to print out any large nested objects using the print function, the result is quite ugly. The beautiful print module pprint of this standard library can print complex structured objects in an easy to read format.

This is a must-have for any Python developer who uses non trivial data structures.

import requests
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)

05 repr

When defining a class or object in Python, it is useful to provide an "official" way to represent the object as a string. For example:

>>> file = open('file.txt', 'r') 
>>> print(file) 
<open file 'file.txt', mode 'r' at 0x10d30aaf0>

This makes it easier to debug code. Add it to your class definition as follows:

class someClass: 
    def __repr__(self): 
        return "<some description here>"
someInstance = someClass()
# Print < some description here >
print(someInstance)

06 sh

Python is a great scripting language. Sometimes using standard os and subprocess may be a bit of a headache.

The SH library allows you to call any program like a normal function - very useful for automating workflows and tasks.

import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')

07 Type hints

Python is a dynamically typed language. You do not need to specify a data type when defining variables, functions, classes, etc. This allows fast development time. However, nothing is more annoying than runtime errors caused by simple input problems.

Starting with Python 3.5, you can choose to provide type hints when defining functions.

def addTwo(x : Int) -> Int:
    return x + 2

You can also define type aliases.

from typing import List
Vector = 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 result
x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]
z = addMatrix(x, y)

Although not mandatory, type annotations can make your code easier to understand.

They also allow you to use type checking tools to catch spurious typeerrors before running. This is useful if you are dealing with large and complex projects!

08 uuid

A quick and easy way to generate a universal unique ID (or "UUID") through the UUID module of the Python standard library.

import uuid
user_id = uuid.uuid4()
print(user_id)

This creates a random 128 bit number that is almost certainly unique. In fact, more than 2 can be generated ¹²² Possible UUID s. But more than five decimal (or 5000000000000000000).

The probability of finding duplicates in a given set is very low. Even if there are a trillion UUID s, the possibility of repetition is far less than one in a billion.

09 wikipedia

wikipedia has a great API that allows users to programmatically access unparalleled and completely free knowledge and information. The wikipedia module makes it easy to access the API.

import wikipedia
result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
    print(link)

Like real sites, this module provides multilingual support, page disambiguation, random page retrieval, and even a donate() method.

10 xkcd

Humor is a key feature of the python language. It is named after the British comedy sketch Python Flying Circus. Many of Python's official documents cite the program's most famous sketches. However, python humor is not limited to documentation. Try running the following functions:

import antigravity

11 zip

The finale is also a great module. Have you ever encountered the need to form a dictionary from two lists?

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))

The zip() built-in function requires a series of iteratable objects and returns a list of tuples. Each tuple groups the elements of the input object by location index.

You can also "unzip" the object * zip() by calling the object.

12 emoji

emoji is a visual emotional symbol used in wireless communication in Japan. It draws pictures, and words refer to characters. It can be used to represent a variety of expressions, such as smiling face for laughter, cake for food, etc. In Chinese mainland, emoji is usually called "little yellow face" or emoji.

# Installation module
pip install emoji
# Give it a try
from emoji import emojize
print(emojize(":thumbs_up:"))

13 howdoi

When you use the terminal terminal to program, you will search for answers on StackOverflow after encountering problems, and then return to the terminal to continue programming. At this time, you sometimes don't remember the solutions you found before. At this time, you need to review StackOverflow again, but you don't want to leave the terminal. Then you need to use this useful command-line tool howdoi.

pip install howdoi

No matter what questions you have, you can ask it and it will try its best to reply.

howdoi vertical align css
howdoi for loop in java
howdoi undo commits in git

But please note - it will regenerate the code captured in the best answer of StackOverflow. It may not always provide the most useful information

howdoi exit vim

14 Jedi

The Jedi library is an autocomplete and code analysis library. It makes writing code faster and more efficient.

Unless you are developing your own IDE, you may be interested in using Jedi as an editor plug-in. Fortunately, there is already a load available!

15 **kwargs

There are many milestones in learning any language. Using Python and understanding the mysterious * * kwargs syntax may count as an important milestone.

The double asterisk * * kwargs in front of the dictionary object allows you to pass the contents of the dictionary to the function as a named parameter.

The key to the dictionary is the parameter name, and the value is the value passed to the function. You don't even need to call it kwargs!

dictionary = {"a": 1, "b": 2}
def someFunction(a, b):
    print(a + b)
    return
# These do the same thing:
someFunction(**dictionary)
someFunction(a=1, b=2)

This is useful when you want to write a function that can handle undefined named parameters.

last

python is a very diverse and well-developed language, so there will certainly be many functions I haven't considered. If you want to know more about python modules, you can praise and pay attention

Keywords: Python

Added by peanutgallery83 on Fri, 24 Dec 2021 21:28:59 +0200