Python is one of the most popular and popular programming languages in the world. There are many reasons for this:

  • It’s easy to learn
  • It’s super versatile
  • It has a large number of modules and libraries

As a data scientist, it’s part of my inner job to use Python every day. In the process, I picked up some useful skills and insights.

Here, I’m trying to share some of them in A to Z order.

Most of these “tricks” are things I use or stumble upon in my daily work. Some I found while browsing the Python standard library documentation. Others were found through PyPi searches.

But credit it – I found four or five of them on awesome-python.com. This is a handpicked list of hundreds of interesting Python tools and modules. This is inspiration worth browsing!

all or any

One of the reasons Python is such a popular programming language is its readability and expressiveness.

People often joke that Python is’ executable pseudocode ‘. But when you can write code like this, it’s hard to argue against:

x = [True, True, False]
if any(x):
    print("At least one True")
if all(x):
    print("Not one False")
if any(x) and not all(x):
    print("At least one True and one False")Copy the code

bashplotlib

Do you want to draw diagrams in the console?

$ pip install bashplotlibCopy the code

You can display charts in the console.

collections

Python has some great default data types, but sometimes they don’t behave the way you want them to.

Fortunately, the Python standard library provides collections modules. This handy add-on gives you more data types.

from collections import OrderedDict, Counter
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
# Counts the frequency of each character
y = Counter("Hello World!")Copy the code

DIR

Ever wondered how to view a Python object and see what properties it has? Of course you do.

From the command line:

>>> dir()
>>> dir("Hello World")
>>> dir(dir)Copy the code

This can be a very useful feature when running Python interactively and dynamically browsing the objects and modules you are working with.

Read more here.

Emoji emoji

Yes, really.

$ pip install emoji
from emoji import emojize
print(emojize(":thumbs_up:"))Copy the code

from __future__ import

One consequence of Python’s popularity is that there are new versions in development all the time. New releases mean new features – unless your version is obsolete.

But fear not. This __future__ module lets you import functionality from future versions of Python. It’s actually like time travel, magic or something.

from __future__ import print_function
print("Hello World!")Copy the code

Why don’t you import curly braces?

geopy

Geography can be a challenging area for programmers (HA, a PUN!). . But the Geopy module makes it very simple.

pip install geopyCopy the code

It works by abstracting out a set of apis for different geocoding services. It allows you to get a place’s full street address, latitude, longitude, and even height.

There is also a useful distance class. It calculates the distance between two positions in your favorite unit of measurement.

from geopy import GoogleV3
place = "221b Baker Street, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)Copy the code

howdoi

Running into a coding problem and forgetting the solution you’ve seen before? Need to check StackOverflow, but don’t want to leave the terminal?

Then you need this useful command line tool.

$ pip install howdoiCopy the code

Ask you any questions and it will try to answer them.

$ howdoi vertical align css 
$ howdoi for java in java 
$ howdoi undo commits in gitCopy the code

Note – it removes code from StackOverflow’s top answer. It may not always provide the most useful information……

$howdoi exits vimCopy the code

Inspect to check

Python’s inspection module is perfect for understanding what’s going on behind the scenes. You can even call its methods yourself!

The following code example inspect.getSource () is used to print your own source code. It also inspect.getModule () is used to print the module that defines it.

The last line prints out its own line number.

import inspect
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)Copy the code

Of course, beyond these trivial uses, examining modules is very useful for understanding what your code does. You can also use it to write self-documenting code.

Jedi

The Jedi library is a code assist and code analysis library. It makes writing code faster and more efficient.

Unless you’re developing your own IDE, you’re probably most interested in using Jedi as an editor plug-in. Fortunately, it’s already available!

However, you are probably already using Jedi. The IPython project uses Jedi for its code completion.

** kwargs

There are many milestones along the way in learning any language. With Python, understanding the arcane **kwargs syntax might count as one.

The double star in front of the dictionary object allows you to pass the contents of the dictionary to functions as named arguments.

The keys of the dictionary are the parameter names and the values are the values 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)Copy the code

This is useful when you want to write functions that can handle named parameters that have not been defined in advance.

List comprehensions

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

These expressions can easily be written in very clean code, almost like natural language.

You can learn more about how to use them here.

Numbers = [1,2,3,4,5,6,7for 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

map

Python supports functional programming with many built-in features. The most useful of these is the map() function – especially in combination with lambda functions.

x = [1, 2, 3]
y = map(lambda x : x + 1 , x)
# prints out [4] 2
print(list(y))Copy the code

In the example above, map() applies a simple lambda function to each element x. It returns a map object that can be converted to some iterable, such as a list or tuple.

newspaper3k

If you haven’t seen it yet, get ready to have your mind blown by Python’s newspaper module.

It allows you to retrieve news articles and related metadata from a range of leading international publications. You can retrieve images, text, and author names.

It even has some built-in NLP features.

So if you are thinking of using BeautifulSoup or another DIY web crawler library for your next project, please save yourself time and effort and use ‘$PIP Install Newspaper3K instead.

Operator overloading Operator overloading

Python provides support for operator overloading, which is one of those terms that makes you sound like a legitimate computer scientist.

It’s actually a simple concept. Ever wonder why Python allows you to add numbers and concatenation strings using the + operator? That’s operator overloading at work.

You can define objects that use Python’s standard operator notation in your own particular way. This allows you to use them in a context relevant to the objects you are working with.

class Thing:
    def __init__(self, value):
        self.__value = value
    def __gt__(self, other):
        return self.__value > other.__value
    def __lt__(self, other):
        return self.__value < other.__value
something = Thing(100)
nothing = Thing(0)
# True
something > nothing
# False
something < nothing
# Error
something + nothingCopy the code

pprint

Python’s default print function does the job. But trying to print out any large nested objects is pretty ugly.

This is where the Standard Library’s Pretty – Print Module comes in. It prints complex structured objects in an easy-to-read format.

Essential for any Python developer working with unconventional data structures.

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

The Queue Queue

Python supports multithreading, which is facilitated by the library’s queue module.

This module allows you to implement queue data structures. These are data structures that allow you to add and retrieve items according to specific rules.

A ‘first in, first out’ (or FIFO) queue allows you to retrieve objects in the order they were added. Last in, first out (LIFO) queues allow you to access recently added objects first.

Finally, priority queues allow you to retrieve objects based on their sorting order.

This is an example of how to use queues for multithreaded programming in Python.

__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 the code easier. Add it to your class definition as follows:

class someClass:
    def __repr__(self):
        return "<some description here>"
someInstance = someClass()
# prints <some description here>
print(someInstance)Copy the code

SH

Python is a great scripting language. Sometimes using standard operating systems and subprocess libraries can be a pain.

The SH library provides a neat alternative.

It allows you to call any program as if it were a normal function – very useful for automating workflows and tasks, all from Python.

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

Type hints

Python is a dynamically typed language. When defining variables, functions, classes, etc., you do not need to specify data types.

This allows for fast development time. However, there are some things more annoying than run-time errors caused by simple typing problems.

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

def addTwo(x : Int) -> Int:
    return x + 2Copy 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 += [a[i][j] + b[i][j]]
    result += [result_row]
  returnThe result of 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

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

They also allow you to catch stray TypeErrors at run time using type checking tools. If you’re working on a large complex project, it might be worth it!

uuid

A quick way to generate a universal unique ID (or “UUID”) is through 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 12 2 possible UUID can be generated. The more than fifty quadrillion (or 5000000000000000000000000000000000000000).

The probability of finding a repeat in a given set is very low. Even with trillions of UUID, the probability of a repeat is far less than one in a billion.

Two lines of code is pretty good.

Virtual environments

This is probably my favorite thing about Python.

It is possible that you are working on multiple Python projects at any one time. Unfortunately, sometimes two projects will depend on different versions of the same dependency. What do you have installed on your system?

Fortunately, Python’s support for virtual environments gives you the best of both worlds. From the command line:

python -m venv my-project
source my-project/bin/activate
pip install all-the-modulesCopy the code

You can now run separate versions and Python installations on the same computer.

Wikipedia

Wikipedia has a great API that allows users to programmatically access unmatched and completely free knowledge and information.

The Wikipedia module makes access to the API almost surprisingly easy.

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

Like real sites, the module offers support for multiple languages, page disambiguation, random page retrieval, and even a donate() method.

XKCD

Humour is a key feature of the Python language – after all, it is named after the British comedy sketch Monty Python’s Flying Circus. Most official Python documentation cites the show’s most famous sketch.

But humor is not limited to documentation. Please run as follows:

import antigravityCopy the code

Never change, Python. Never change.

YAML

YAML stands for ‘YAML Is Not Markup Language’. It is a data formatting language that is a superset of JSON.

Unlike JSON, it can store more complex objects and reference its own elements. You can also write comments that make them particularly suitable for writing configuration files.

The PyYAML module lets you use Python with YAML. Installation:

$ pip install pyyamlCopy the code

Then import it into your project:

import yamlCopy the code

PyYAML allows you to store Python objects of any data type, as well as instances of any user-defined class.

zip

That’s the last trick. It’s really cool. Ever need 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” objects by calling *zip() them.

Thanks for reading!

英文原文

See more articles

Public Account: Milky Way No. 1 Email: [email protected]