Top 10 Tips & Tricks For Pythonistas!

Top 10 Tips & Tricks For Pythonistas!

ยท

8 min read

You and I can certainly confirm and agree that Python code is one of the shortest, best languages and has an easy to learn syntax with a wide range of use-cases!

Do you know that there are tricks and tips that could help you increase your code efficiency and still be readable and understandable?

Today I'll share my top 10 Python tricks & tips that most Pythonistas do not tell you about.

image.png โญImage Credit: Pythonista Cafe

Please note that some may not be beginner-friendly and you may take a while to grasp them and start using them in your projects.

Let's roll ๐Ÿš€๐Ÿš€

๐Ÿ”น The Walrus(:=) Operator

Each new version of Python adds new features to the language. For Python 3.8, the biggest change was the addition of assignment expressions.

Specifically, the :=operator gives you a new syntax for assigning variables in the middle of expressions.

Consider the code below

my_blog = "blog.octachart.com"

blog_len = len(my_blog)
if blog_len > 10:
    print(True)

But with this operator, we can create variables amidst code.

my_blog = "blog.octachart.com"
if (blog_len := len(my_blog) > 10):
    print(True)

๐Ÿ”น The dir() function

dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object.

import pip
print(dir(pip))

Running the above outputs;

image.png

๐Ÿ”น The * operator

The asterisk operator (*) is used to unpack all the values of an iterable. Consider the examples below

num_1 = [1,2,3,4,5]
print(*num_1)

You can easily merge two lists ;

num_2 = [6,7,8,9,10]
print([*num_1, *num_2])

In the above examples, we could have used a bunch of for loop statements to achieve the same thing ;

new = []
for n1 in num_1:
    new.append(n1)

for n2 in num_2:
    new.append(n2)
print(new)

โœ” *args
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list.

Example

def names(*args):
    return args
print(names("Ronnie", "Atuhaire", "John"))

* args is a tuple because it receives a tuple containing the positional arguments beyond the formal parameter list.

โœ” **kwargs
The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list.

def names_(**kwargs):
    return kwargs
print(names_(first = "Ronnie", last = "Atuhaire"))

๐Ÿ”น The breakpoint()

The Python breakpoint() built-in function is a tool that allows developers to set points in code at which a debugger is called.

By default, this function results in an instantiation of Python's native debugger class.
Example;

x = 10
y = 'Hi'
z = 'Hello'

print(y)
breakpoint()
print(z)

Python 3.7 introduced breakpoint() method that allows us to write loosely coupled debugging code.
The above code created a session of pdb.set_trace() and so it is a pretty easy way of calling the pdb debugger.

If we pressed for instance c for continue , the next execution would follow.

image.png

Read more about the pdb module

๐Ÿ”น The zip() function

The zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator.

This iterator generates a series of tuples containing elements from each iterable.

You can use the zip() function to combine several lists of the same length and print out the result.

Example;

string_ = ["one", "two", "three"]
number_ = [1,2,3]

for string, number in zip(string_ , number_):
    print(string, "-->" ,number)

You can also use it alongside the * operator to achieve the same thing above.

mat = [[1, 2, 3], [1000, 2000, 3000]]
print([n for n in zip(*mat)])

Note: I am using python comprehensions in the above example which is a topic and a trick that I won't cover in this article, so please refer to this article of mine about comprehensions.

๐Ÿ”น The _ Operator

It's neither an operator nor a function. It's a variable that automatically gets assigned the result of each expression executed by the shell.

Example;

image.png In the above case, underscore (_) when typed into the interpreter will return the value of the last executed statement.

It can also be used in a loop as a throwaway to indicate that the variable is not going to be used.

for _, idx in enumerate(range(2,10)):
    print(idx)

๐Ÿ”น Multiple user inputs

Python has an input() function that lets you ask a user for some text input. You call this function to tell the program to stop and wait for the user to key in.

For example, if we wanted to have multiple user inputs at the same time storing them in different variables, we would achieve that like this;

first_name = input("Enter your first name [+]: ")
last_name = input("Enter your last name [+]: ")

print(f"So you are {first_name} {last_name} all along!")

What if I told you that you can actually do this;

first_name_ , last_name_ = input("Enter your full name [+]: ").split()
print(f"So you are {first_name_} {last_name_} all along!")

Output >> image.png

๐Ÿ”น Shut down a computer

The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules.

With it, you can shutdown, restart or logoff with python commands instead of GUI:

import os
os.system('shutdown -s')

The os.system(command) executes the command (a string) in a subshell.

Read more about os [module](https://docs.python.org/3/library/os.html) to see the available options

๐Ÿ”น Python Pretty Printer

The pprint module provides a capability to pretty-print arbitrary Python data structures in a form that can be used as input to the interpreter.

Let us consider this code I used in Geolocating IPs in the article I wrote sometime back:

import requests
import json

# IP address to test
ip_address = '200.229.2.90'

# Our Endpoint (API) URL
request_url = f"https://geolocation-db.com/jsonp/{ip_address}"

# Send request and decode the result
response = requests.get(request_url)
result = response.content.decode()

# Clean the returned string so it just contains the JSON String
result = result.split("(")[1].strip(")")

# Into dict
result = result.split("(")[1].strip(")")

print(result)

Running the above returns;

image.png

What if we used Python Pretty Printer

import requests
import json
import pprint

# IP address to test
ip_address = '200.229.2.90'

# Our Endpoint (API) URL
request_url = f"https://geolocation-db.com/jsonp/{ip_address}"

# Send request and decode the result
response = requests.get(request_url)
result = response.content.decode()

# Clean the returned string so it just contains the JSON String
result = result.split("(")[1].strip(")")

# Convert this data into dictionary
result  = json.loads(result)


pp = pprint.PrettyPrinter(indent=1)
pp.pprint(result)

The output >> image.png

๐Ÿ”น PIP useful commands

PIP is a recursive acronym that can stand for either "Pip Installs Packages" or "Pip Installs Python". Alternatively, pip stands for "preferred installer program"

PIP is a package manager for Python packages, or modules if you like and If you have Python version 3.4 or later, PIP is included by default.

โœ” pip_search
Looking for a package, pip_search is there to help you out without leaving the terminal.

pip_search allows you to search PyPI for any package using the pip_search <package> command.

The original pip search deprecated and the API was shut down due to being overwhelmed but luckily there is always a way;

First pip install pip-search

pip_search pygame

The output >>> image.png

โœ” pip show
Itโ€™s very common to get details about a package that is currently installed. For any package, this command returns details like name, version, summary, dependent packages and much more.

pip show django

Output >> image.png

โœ” pip check
pip-check gives you a quick overview of all installed packages and their update status. image.png

โœ” pip --no-cache-dir
There is also a concept called caching. pip provides a cache that functions similarly to that of a web browser and it is on by default. We can disable the cache and always access the PyPI using the โ€“no-cache-dir option as:

pip install --no-cache-dir flask

๐Ÿ”น Keywords

We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive.

from keyword import kwlist

def all_keywords():
    print(kwlist, end="\n\n")
    return f"And they are {len(kwlist)} keywords in Python 3.10.0"

print(all_keywords())

The Output >>>

image.png From the output, we can say that there are currently 35 keywords in Python 3.10.0

Find all the code here

๐Ÿ”ธ Summary

Did you count them ๐Ÿ™‚? Well, there is an extra bonus tip (Keywords) from me to you!

Obviously, there are cooler tricks that I may have not yet discovered but I will keep digging.

In case you want to learn more about Python comprehensions and have a basic understanding of how they work. Read my article here.

The Zen of Python --> I have a full article coming out any time about this, so you may want to stay connected.

๐Ÿ”ธ Conclusion

Once again, hope you learned something today from my little closet.

Please consider subscribing or following me for related content, especially about Tech, Python & General Programming.

You can show extra love by buying me a coffee to support this free content and I am also open to partnerships, technical writing roles, collaborations and Python-related training or roles.

Buy Ronnie A Coffee ๐Ÿ“ข You can also follow me on Twitter : โ™ฅ โ™ฅ Waiting for you! ๐Ÿ™‚
ย