Hello, I’m Chi Ye
Here, IN this article, I’ve briefly introduced 15 extremely useful Python tricks that you might find useful if you’re interested in one or more of them.
01 all or any
One of the many reasons the Python language is so popular is that it is very readable and expressive.
People often joke that Python is executable pseudocode. When you can write code like this, it’s hard to argue.
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")Copy the code
02 dir
Ever wonder how to look inside a Python object to see what properties it has? On the command line, enter:
dir()
dir("Hello World")
dir(dir)
Copy the code
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.
The derivation of the list
One of my favorite things about Python programming is its list derivations.
These expressions can easily be written into 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)Copy the code
04 pprint
Python’s default print function does its job. But if you try to print out any large nested objects using the print function, the results are pretty ugly. The library’s nifty print module, PPrint, prints 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)Copy the code
05 repr
When defining a class or object in Python, it is useful to provide an “official” way to represent that object as a string. Such as:
>>> file = open('file.txt', 'r')
>>> print(file)
<open file 'file.txt', mode 'r' at 0x10d30aaf0>
Copy the code
This makes debugging code much easier. 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)Copy the code
06 sh
Python is a great scripting language. Sometimes using standard OS and subprocesses can be a bit of a headache for Cook.
The SH library lets you call any program just like a normal function — 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! ')Copy the code
07 Type hints
Python is a dynamically typed language. You do not need to specify data types when defining variables, functions, classes, and so on. This allows for fast development times. However, nothing is more annoying than a run-time error caused by a simple input problem.
Starting with Python 3.5, you can choose to provide type hints when defining functions.
def addTwo(x : Int) -> Int:
return x + 2
Copy the code
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 + = [[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)Copy the code
Although not mandatory, type annotations can make your code easier to understand.
They also allow you to use type-checking tools to catch stray TypeErrors before they run. This is useful if you are working on large, complex projects!
08 uuid
A quick and easy way to generate a universal unique ID (or “UUID”) from the UUID module of the Python standard library.
import uuid
user_id = uuid.uuid4()
print(user_id)
Copy the code
This creates a random 128-bit number that is almost certainly unique. In fact, more than 2¹²² of possible UUID can be generated. But more than five decimal (or 5000000000000000000000000000000000000).
The probability of finding a repetition in a given set is extremely low. Even with a trillion UUID, the probability of a repeat is far less than one in a billion.
09 wikipedia
Wikipedia has a great API that allows users to programmatically access unmatched and completely free knowledge and information. The Wikipedia module makes accessing the API very easy.
import wikipedia
result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
print(link)
Copy the code
Like the real site, the module offers multilingual support, page disambiguation, random page retrieval, and even a donate() method.
10 xkcd
Humor is a key feature of the Python language, named after the British comedy sketch show Python Flying Circus. Many official Python documents refer to the show’s most famous sketches. However, Python humor is not limited to documentation. Try running the following function:
import antigravity
Copy the code
11 zip
The last one is also a great module. Have you ever had to form a dictionary from two lists?
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
Copy the code
The zip() built-in function takes a list of iterable objects and returns a list of tuples. Each tuple groups the elements of the input object by positional index.
You can also “unzip” the object *zip() by calling it.
12 emoji
Emoji is a visual emotional symbol used in Wireless communication in Japan, drawing pictures and text refers to characters, which can be used to represent a variety of expressions, such as smiling face for laughter, cake for food, etc. In mainland China, they are commonly known as “little yellow faces”, or emoji.
Emojize print(emojize(":thumbs_up:"))Copy the code
13 howdoi
When you program with terminal terminal, you will search for the answer on StackOverflow after encountering a problem, and then go back to the terminal to continue programming. Sometimes you don’t remember the solution you found before, and you need to check StackOverflow again without leaving the terminal. At this point you need to use the useful command line tool howdoi.
pip install howdoi
Copy the code
No matter what questions you have, you can ask it and it will try to reply.
howdoi vertical align css
howdoi for loop in java
howdoi undo commits in git
Copy the code
But be warned — it regenerates the code from StackOverflow’s best answers. It may not always provide the most useful information……
howdoi exit vim
Copy the code
14 Jedi
The Jedi library is an autocomplete and code analysis library. It makes writing code faster and more efficient.
Unless you’re developing your own IDE, you might 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. Working with Python and understanding the arcane **kwargs syntax may count as an important milestone.
The double star in front of the dictionary object ****kwargs** allows you to pass the contents of the dictionary to functions as named arguments.
The key to a 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 function (a, b): print(a + b) return # these do the same thing: someFunction(**dictionary) someFunction(a=1, b=2)Copy the code
This is useful when you want to write functions that can handle named parameters that are not predefined.
The last
Python is a very diverse and well-developed language, so there are certainly many features I hadn’t considered. If you want to learn more about Python modules, give a like and follow