0xploit.com

General-Purpose 26 Useful Python Tips and Tricks

Joined
Dec 29, 2021
Messages
29
Hellcoins
♆711
Python is one of the most popular and in-demand programming languages. There are several reasons for this:

  • It's easy to learn.
  • He is very versatile.
  • It has many modules and libraries.
In the process of working with Python, everyone finds some useful modules and tricks for themselves. In this collection, you will learn about some useful tricks.

all and any
One of the many reasons for Python's popularity is its readability and expressiveness.

It's often joked that Python is "executable pseudocode". However, when you can write code like this, it becomes hard to disagree:
You must reply before you can see the hidden data contained here.
bashplotlib
Want to plot in the console?
You must reply before you can see the hidden data contained here.
Build for health.

collections
Python has some cool built-in data types, but sometimes they don't behave quite the way you want them to.

Fortunately, the built-in Python library has a collections module with handy additional data types:
You must reply before you can see the hidden data contained here.
dir
Ever wondered how to look inside an object in Python and look at its attributes? Of course we thought about it.

We use the command line:
You must reply before you can see the hidden data contained here.
This can be useful for an interactive session in Python, as well as for dynamically exploring the objects and modules you are working with.

More can be found in the official documentation.

emoji
Yes, seriously.

$ pip install emoji

And don't pretend you don't want to try:
You must reply before you can see the hidden data contained here.
?

from future import
One consequence of Python's popularity is that new versions are constantly being developed and released. New versions - new features, but not for you if you are using an outdated one.

However, not everything is so bad. The future module makes it possible to import the functionality of future versions of Python. It's just like time travel, or magic:
You must reply before you can see the hidden data contained here.
Why not try importing curly braces?

geopy It
can be difficult for programmers to navigate geography. However, the geopy module simplifies things:
You must reply before you can see the hidden data contained here.
It works by abstracting the APIs of different geocoding services. This module makes it possible to find out the full address of a place, its longitude and latitude, and even its altitude.

It also has a useful Distance class. It calculates the distance between two places in a convenient unit of measure.
You must reply before you can see the hidden data contained here.
howdoi
Stuck on a problem and can't remember the solution? Need to go to StackOverflow but don't feel like leaving the terminal?

Then you can't do without this command line tool:
You must reply before you can see the hidden data contained here.
Ask any question and he will try to find the answer to it:
You must reply before you can see the hidden data contained here.
But beware: it pulls code from the top StackOverflow answers and doesn't always provide useful information:
You must reply before you can see the hidden data contained here.
inspect
The inspect module is useful for understanding what goes on behind the scenes in Python. You can even call its methods on them!

The following uses the inspect.getsource() method to display its own source code. It also uses the inspect.getmodule() method to display the module in which it was defined.

The last command prints the line number it is on:
You must reply before you can see the hidden data contained here.
Of course, apart from such banal uses, this module can be useful for understanding what your code is doing. You can also use it to write self-documenting code.

Jedi
The Jedi library is designed for code completion and analysis. It speeds up the process of writing code and makes it more productive.

If you're not developing your own IDE, then you'll probably be more interested in using Jedi as an editor extension. Fortunately, there are already many options.

You may have already met Jedi - IPython uses this library for autocompletion.

** kwargs
When learning any language, there are many cornerstones along the way. In the case of Python, understanding the mysterious **kwargs syntax can be considered one of them.

The two asterisks in front of the dictionary object make it possible to pass the contents of this dictionary to the function as named arguments.

The keys of the dictionary are the names of the arguments, and the values are passed to the function. You don't even have to call it kwargs:
You must reply before you can see the hidden data contained here.
This is useful in cases where your functions need to handle named arguments that are not predefined.

Note transl. It can also come in handy when writing wrapper functions that pass all arguments to another function.

List Generators
Another cool feature of Python that allows you to quickly create lists. Such expressions make it easy to write clean code that reads almost like natural language:
You must reply before you can see the hidden data contained here.
map
Python has good built-in support for functional programming. One of the most useful features is the map() function, especially when combined with lambda functions:
You must reply before you can see the hidden data contained here.
Here, map() applies a simple lambda function on each element of x and returns a map object that can be converted to some iterable object like a list or a tuple.

newspaper3k
If you haven't met him yet, get ready for the newspaper module to blow your mind.

It allows you to extract articles and related metadata from many different sources. You can extract images, text, and author names.

It even has built-in NLP functionality.

So if you were going to use BeautifulSoup or another web scraping library in your next project, save yourself some time and effort and install newspaper:
You must reply before you can see the hidden data contained here.
Operator Overloading
Python has support for operator overloading, one of those things that all real computer scientists talk about.

Actually, the idea is simple. Ever wondered why Python allows you to use the + operator to both add numbers and concatenate strings? This is what operator overloading is all about.

You can define objects that use standard operator symbols in any way. This allows you to apply them in the context of the objects you are working with:
You must reply before you can see the hidden data contained here.
pprint
The standard Python print() function does the trick. But if you try to display some large nested object, the result will not look very nice.

This is where the pprint (pretty print) standard library module comes to the rescue. With it, you can display objects with a complex structure in a readable form.

A must have for any Python developer working with non-standard data structures:
You must reply before you can see the hidden data contained here.
Queue
Python supports multithreading, which is helped by the standard Queue module.

It allows you to implement a data structure such as a queue. Queues allow you to add and remove elements according to a certain rule.

First in, first out (FIFO) queues allow you to retrieve objects in the order they were added. From the "last in, first out" (LIFO) queues, you can retrieve the last added objects.

Finally, priority queues allow objects to be retrieved according to their sort order.

Here you can see an example of using queues in multi-threaded Python programming.

repr
When defining a class or object, it's useful to add an "official" way to represent an object as a string. For example:
You must reply before you can see the hidden data contained here.
This greatly simplifies debugging. Here's all you need to do:
You must reply before you can see the hidden data contained here.
Note transl. The repr () method allows you to define a string representation that is intended for the programmer and is convenient for use during debugging, and the str () method allows you to define a user-friendly string representation that can be displayed in the program interface.

sh
Python is a great scripting language. But sometimes the standard os and subprocess libraries only cause headaches.

The sh library can be a nice alternative.

It allows you to call any program as a normal function, which is useful for automating various tasks purely with Python:
You must reply before you can see the hidden data contained here.
Note transl. The sh library only supports Linux and macOS platforms; to work on Windows, you will have to look for another tool.

Type Annotations
Python is a dynamically typed language. You don't need to specify the data type when defining variables, functions, classes, etc.

This allows you to speed up the development process. However, few things are more annoying than a run-time error caused by a simple type mismatch.

Since Python 3.5, you can add type annotations when defining a function:
You must reply before you can see the hidden data contained here.
You can even define type aliases:
You must reply before you can see the hidden data contained here.
Although their use is optional, using type annotations can make the code more understandable.

They also allow you to use type checking tools to catch TypeErrors.

uuid
The uuid standard module is a quick and easy way to generate a universally unique identifier (UUID).
You must reply before you can see the hidden data contained here.
This is how we create a random 128-bit number that will almost certainly be unique.

There are over 2¹²² possible UUIDs. That's over 5 undecillions 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 small. Even with a trillion UUIDs, the odds that there is a duplicate among them is far less than one in a billion.

Pretty good for two lines of code.

Virtual Environments
Python programmers often work on multiple projects at the same time. Unfortunately, sometimes two projects depend on different versions of the same dependency. Which one to install?

Luckily, Python has support for virtual environments that let you get the best of both worlds. On the command line you need to enter:
You must reply before you can see the hidden data contained here.
Now you can have different independent versions of Python on the same machine.

wikipedia
Wikipedia has a cool API that allows you to access an unrivaled source of completely free information.

The wikipedia module makes accessing this API almost overly convenient:
You must reply before you can see the hidden data contained here.
Like a real site, the module provides multilingual support, page disambiguation, getting a random page, and even a donate() method.

xkcd
Humor is a key feature of Python. The language was eventually named after the British comedy show Monty Python's Flying Circus. In many places in the official documentation you can find references to the most famous episodes of the show.

Of course, the sense of humor doesn't end with the documentation. Try entering the following line:
You must reply before you can see the hidden data contained here.
Be yourself, Python. Be yourself.

YAML
YAML stands for "YAML Ain't Markup Language". It is a data formatting language that is a superset of JSON.

Unlike JSON, YAML can store more complex objects and refer to its own elements. You can also write comments there, which makes YAML suitable for configuration files.

The PyYAML module allows you to use YAML in Python. You can install like this:
You must reply before you can see the hidden data contained here.
And then import:
You must reply before you can see the hidden data contained here.
PyYAML allows you to store any Python objects and instances of any custom classes.

zip
Finally, one more cool thing. Ever needed to create a dictionary from two lists?
You must reply before you can see the hidden data contained here.
The built-in zip() function takes multiple iterables and returns a sequence of tuples. Each tuple groups the elements of the objects by their index.

You can do the reverse of zip() with zip(*).

What tricks or useful libraries do you know? Share in the comments.
 
Top