AZ trik Python yang berguna

Python adalah salah satu bahasa pemrograman yang paling populer dan banyak permintaan di dunia. Ini karena banyak alasan:

  • mudah dipelajari
  • itu sangat serbaguna
  • itu memiliki sejumlah besar modul dan perpustakaan

Saya menggunakan Python setiap hari sebagai bagian integral dari pekerjaan saya sebagai ilmuwan data. Sepanjang jalan, saya telah mengambil beberapa trik dan tip berguna.

Di sini, saya telah membagikan beberapa di antaranya dalam format AZ.

Sebagian besar 'trik' ini adalah hal-hal yang saya gunakan atau temukan selama pekerjaan saya sehari-hari. Beberapa saya temukan saat menjelajahi dokumen Python Standard Library. Beberapa lainnya saya temukan mencari melalui PyPi.

Namun, kredit saat jatuh tempo - saya menemukan empat atau lima di antaranya di awesome-python.com. Ini adalah daftar hasil kurasi dari ratusan alat dan modul Python yang menarik. Layak untuk dijelajahi untuk mendapatkan inspirasi!

semua atau apapun

Salah satu dari banyak alasan mengapa Python menjadi bahasa yang begitu populer adalah karena ia mudah dibaca dan ekspresif.

Sering bercanda bahwa Python adalah 'pseudocode yang dapat dieksekusi'. Tetapi ketika Anda dapat menulis kode seperti ini, sulit untuk membantah sebaliknya:

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")

bashplotlib.dll

Anda ingin memplot grafik di konsol?

$ pip install bashplotlib

Anda dapat memiliki grafik di konsol.

koleksi

Python memiliki beberapa tipe data default yang bagus, tetapi terkadang mereka tidak akan berperilaku persis seperti yang Anda inginkan.

Untungnya, Python Standard Library menawarkan modul koleksi. Add-on praktis ini memberi Anda tipe data lebih lanjut.

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!") 

dir

Pernah bertanya-tanya bagaimana Anda bisa melihat ke dalam objek Python dan melihat atribut apa yang dimilikinya? Tentu saja Anda punya.

Dari baris perintah:

>>> dir() >>> dir("Hello World") >>> dir(dir)

Ini bisa menjadi fitur yang sangat berguna saat menjalankan Python secara interaktif, dan untuk secara dinamis menjelajahi objek dan modul yang Anda kerjakan.

Baca lebih lanjut di sini.

emoji

Ya benar.

$ pip install emoji

Jangan berpura-pura Anda tidak akan mencobanya…

from emoji import emojize print(emojize(":thumbs_up:"))

?

dari impor __future__

Salah satu konsekuensi dari popularitas Python adalah selalu ada versi baru yang sedang dikembangkan. Versi baru berarti fitur baru - kecuali jika versi Anda kedaluwarsa.

Namun, jangan takut. Modul __future__ memungkinkan Anda mengimpor fungsionalitas dari versi Python yang akan datang. Ini benar-benar seperti perjalanan waktu, atau sihir, atau sesuatu.

from __future__ import print_function print("Hello World!")

Mengapa tidak mencoba mengimpor kurung kurawal?

geopy

Geografi dapat menjadi medan yang menantang bagi pemrogram untuk dinavigasi (ha, a pun!). Tetapi modul geopy membuatnya sangat mudah.

$ pip install geopy

Ia bekerja dengan mengabstraksi API dari berbagai layanan geocoding yang berbeda. Ini memungkinkan Anda mendapatkan alamat jalan lengkap, lintang, bujur, dan bahkan ketinggian suatu tempat.

Ada juga kelas jarak jauh yang berguna. Ini menghitung jarak antara dua lokasi di unit pengukuran favorit Anda.

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

bagaimana saya

Terjebak pada masalah pengkodean dan tidak dapat mengingat solusi yang Anda lihat sebelumnya? Perlu memeriksa StackOverflow, tetapi tidak ingin meninggalkan terminal?

Maka Anda membutuhkan alat baris perintah yang berguna ini.

$ pip install howdoi

Ajukan pertanyaan apa pun yang Anda miliki, dan itu akan melakukan yang terbaik untuk memberikan jawaban.

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

Berhati-hatilah - ini mengambil kode dari jawaban teratas dari StackOverflow. Mungkin tidak selalu memberikan informasi yang paling berguna…

$ howdoi exit vim

memeriksa

Modul inspeksi Python sangat bagus untuk memahami apa yang terjadi di balik layar. Anda bahkan dapat memanggil metodenya sendiri!

Contoh kode di bawah ini digunakan inspect.getsource()untuk mencetak kode sumbernya sendiri. Ini juga digunakan inspect.getmodule()untuk mencetak modul yang telah ditentukan.

Baris terakhir kode mencetak nomor barisnya sendiri.

import inspect print(inspect.getsource(inspect.getsource)) print(inspect.getmodule(inspect.getmodule)) print(inspect.currentframe().f_lineno)

Tentu saja, di luar penggunaan yang sepele ini, modul inspeksi terbukti berguna untuk memahami apa yang dilakukan kode Anda. Anda juga dapat menggunakannya untuk menulis kode yang mendokumentasikan sendiri.

Jedi

Pustaka Jedi adalah pustaka pelengkapan otomatis dan analisis kode. Itu membuat penulisan kode lebih cepat dan lebih produktif.

Kecuali Anda mengembangkan IDE Anda sendiri, Anda mungkin paling tertarik menggunakan Jedi sebagai plugin editor. Untungnya, sudah banyak tersedia!

Anda mungkin sudah menggunakan Jedi. Proyek IPython memanfaatkan Jedi untuk fungsionalitas pelengkapan otomatis kodenya.

** kwargs

Saat mempelajari bahasa apa pun, ada banyak pencapaian di sepanjang jalan. Dengan Python, memahami **kwargssintaksis misterius mungkin dihitung sebagai satu.

The double-asterisk in front of a dictionary object lets you pass the contents of that dictionary as named arguments to a function.

The dictionary’s keys are the argument 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)

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

List comprehensions

One of my favourite things about programming in Python are its list comprehensions.

These expressions make it easy to write very clean code that reads almost like natural language.

You can read more about how to use them here.

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)

map

Python supports functional programming through a number of inbuilt features. One of the most useful is the map() function — especially in combination with lambda functions.

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

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

newspaper3k

If you haven’t seen it already, then be prepared to have your mind blown by Python’s newspaper module.

It lets you retrieve news articles and associated meta-data from a range of leading international publications. You can retrieve images, text and author names.

It even has some inbuilt NLP functionality.

So if you were thinking of using BeautifulSoup or some other DIY webscraping library for your next project, save yourself the time and effort and $ pip install newspaper3k instead.

Operator overloading

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

It’s actually a simple concept. Ever wondered why Python lets you use the + operator to add numbers and also to concatenate strings? That’s operator overloading in action.

You can define objects which use Python’s standard operator symbols in their own specific way. This lets you use them in contexts relevant to the objects you’re 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  nothing # False something < nothing # Error something + nothing

pprint

Python’s default print function does its job. But try printing out any large, nested object, and the result is rather ugly.

Here’s where the Standard Library’s pretty-print module steps in. This prints out complex structured objects in an easy-to-read format.

A must-have for any Python developer who works with non-trivial data structures.

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

Queue

Python supports multithreading, and this is facilitated by the Standard Library’s Queue module.

This module lets you implement queue data structures. These are data structures that let you add and retrieve entries according to a specific rule.

‘First in, first out’ (or FIFO) queues let you retrieve objects in the order they were added. ‘Last in, first out’ (LIFO) queues let you access the most recently added objects first.

Finally, priority queues let you retrieve objects according to the order in which they are sorted.

Here’s an example of how to use queues for multithreaded programming in Python.

__repr__

When defining a class or an object in Python, it is useful to provide an ‘official’ way of representing that object as a string. For example:

>>> file = open('file.txt', 'r') >>> print(file) 

This makes debugging code a lot easier. Add it to your class definitions as below:

class someClass: def __repr__(self): return "" someInstance = someClass() # prints  print(someInstance)

sh

Python makes a great scripting language. Sometimes using the standard os and subprocess libraries can be a bit of a headache.

The sh library provides a neat alternative.

It lets you call any program as if it were an ordinary function — useful for automating workflows and tasks, all from within Python.

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

Type hints

Python is a dynamically-typed language. You don’t need to specify datatypes when you define variables, functions, classes etc.

This allows for rapid development times. However, there are few things more annoying than a runtime error caused by a simple typing issue.

Since Python 3.5, you have the option 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 compulsory, type annotations can make your code easier to understand.

They also allow you to use type checking tools to catch those stray TypeErrors before runtime. Probably worthwhile if you are working on large, complex projects!

uuid

A quick and easy way to generate Universally Unique IDs (or ‘UUIDs’) is through the Python Standard Library’s uuid module.

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

This creates a randomized 128-bit number that will almost certainly be unique.

In fact, there are over 2¹²² possible UUIDs that can be generated. That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).

The probability of finding duplicates in a given set is extremely low. Even with a trillion UUIDs, the probability of a duplicate existing is much, much less than one-in-a-billion.

Pretty good for two lines of code.

Virtual environments

This is probably my favorite Python thing of all.

Chances are you are working on multiple Python projects at any one time. Unfortunately, sometimes two projects will rely on different versions of the same dependency. Which do you install on your system?

Luckily, Python’s support for virtual environments lets you have the best of both worlds. From the command line:

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

Now you can have standalone versions and installations of Python running on the same machine. Sorted!

wikipedia

Wikipedia has a great API that allows users programmatic access to an unrivalled body of completely free knowledge and information.

The wikipedia module makes accessing this API almost embarrassingly convenient.

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

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

xkcd

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

The sense of humour isn’t restricted to the docs, though. Have a go running the line below:

import antigravity

Never change, Python. Never change.

YAML

YAML stands for ‘YAML Ain’t Markup Language’. It is a data formatting language, and is a superset of JSON.

Unlike JSON, it can store more complex objects and refer to its own elements. You can also write comments, making it particularly suited to writing configuration files.

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

$ pip install pyyaml

And then import into your projects:

import yaml

PyYAML lets you store Python objects of any datatype, and instances of any user-defined classes also.

zip

One last trick for ya, and it really is a cool one. Ever needed to form a dictionary out of two lists?

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

The zip() inbuilt function takes a number of iterable objects and returns a list of tuples. Each tuple groups the elements of the input objects by their positional index.

You can also ‘unzip’ objects by calling *zip() on them.

Thanks for reading!

So there you have it, an A-Z of Python tricks — hopefully you’ve found something useful for your next project.

Python’s a very diverse and well-developed language, so there’s bound to be many features I haven’t got round to including.

Please share any of your own favorite Python tricks by leaving a response below!