Five Python Features You (Probably) Didn’t Know

Five Python Features You (Probably) Didn’t Know
Python has a lot to give. Every week, I see code written in a way that I did not think was possible. Some of these functionalities are brilliant, and I cannot understand how I ever lived without them — others are simply nice to know

Python has a lot to give. Every week, I see code written in a way that I did not think was possible. Some of these functionalities are brilliant, and I cannot understand how I ever lived without them — others are simply nice to know.

This article will cover a few of these functionalities that are less commonly used, while still being immensely useful — including:

Variable Assignments - with *args and **kwargs (incl. dictionary merging)
Frozensets - what they are and why they're useful
Multiple Conditionals - cleaner logic
Check if a Variable Exists - in both local and global scopes
Better than Lambdas - writing Pythonic and functional one liners

Variable Assignment

Just like function *args and **kwargs — we can use the same syntax in our variable assignments:

Image for post


Merge Two Dictionaries

Using the iterable variable assignment method can be particularly useful when merging dictionaries, where we can use the **kwargs syntax:

Image for post
But we need to be cautious. If there are any common keys between the two dictionaries, the latter key-value pair (from y) will replace the former.

With the newest, upcoming version of Python (3.9), we will get a fresh new syntax for this exact problem — the dictionary merge and update operators:

z = x | y  # merge - same behavior as above
x |= y  # update - in-place dictionary merge

Frozensets

In Python, we can use sets, which are unordered collections of distinct objects. These sets are mutable, which means we can change them with add() and remove() — this also means that the set is unhashable (more on this in a moment).

Alternatively, we can use the immutable frozenset() — we cannot change its values. But, because it’s immutable, it’s hashable — which shows when we attempt to use both a set and frozenset as dictionary keys:

Image for post

Okay, so using a frozenset as a dictionary key is not that useful (if anyone has a reason for doing this, please let me know!). But what frozenset does do is give us is more explicit, intentional code. It warns future readers of the code —

Change me and everything will break

A reader has pointed out not just one, but two_ uses for this on Twitter_ — thanks!

Multiple Conditionals

Clean up those messy if-statements. Rather than:

if 0 <= x and x <= 1:
     print('value is %')

We can write:

if (0 <= x <= 1):
    print('value is %')

Taking this a little further, we can add more conditional statements and chain them together with bitwise operators like so:

if (0 <= x < 1) | (7 <= x < 8) | (x == 10):
    print('passed')

Check if a Variable Exists

Need to check if a variable exists?

if "var_name" in globals():
    print("var_name exists!")

elif "var_name" in locals():
    print("var_name exists locally!")
else:
    print("var_name does not exist.")

We can check for variables in both the global and local scopes using globals() and locals() respectively.

Image for post

Checking if the variables test1 and test2 exist in either the global or local scope.

Both scope functions, globals and locals, return dictionaries — so we have also implemented our dictionary merging syntax {**x, **y} above. Our code then checks for both test1 and test2 in this merged scope dictionary.

Better than Lambdas

Using lambdas for quick and easy one-liners is pretty common, but I rarely see it used to build multi-argument functions. What we usually see is something like this:

do_something = lambda x: x**2 / (1 - x)

But they can be used to create elegant one-liner functions:

Image for post

Using the lambda function to create a one-line sample size calculator with Cochran’s formula.

Before we start coding lambdas everywhere, be aware that this is probably one of the most hated uses of syntax in Python — so let’s quickly back-up.

PEP 8 — the style guide for Python — **strongly **discourages the use of lambda as named functions.

At the same time, one-line functions, especially for mathematical formulae, can look amazing.

So, rather than using lambda, we write a one-liner def statement, like so:

Image for post

Using a single line def statement to create a sample size calculator with Cochran’s formula.

Which method you use is up to you. If you want angry mobs with pitchforks chanting your name, use lambda — otherwise, use def.

That’s our five, super useful Python features —

Variable Assignments
Frozensets
Multiple Conditionals
Check if a Variable Exists
Better than Lambdas

I hope a few of these were new to you and will be as helpful for you as they are for me. If you have any suggestions or questions, feel free to reach out via Twitter or in the comments below.

Thanks for reading!

Suggest:

Python Tutorials for Beginners - Learn Python Online

Learn Python in 12 Hours | Python Tutorial For Beginners

Complete Python Tutorial for Beginners (2019)

Python Programming Tutorial | Full Python Course for Beginners 2019

Python Tutorial for Beginners [Full Course] 2019

Introduction to Functional Programming in Python