7.1. Alternative Approach

This section covers some alternatives approaches to work with Python.

7.1.1. Box: Using Dot Notation to Access Keys in a Python Dictionary

!pip install python-box[all]

Do you wish to use dict.key instead of dict['key'] to access the values inside a Python dictionary? If so, try Box.

Box is like a Python dictionary except that it allows you to access keys using dot notation. This makes the code cleaner when you want to access a key inside a nested dictionary like below.

from box import Box

food_box = Box({"food": {"fruit": {"name": "apple", "flavor": "sweet"}}})
print(food_box)
{'food': {'fruit': {'name': 'apple', 'flavor': 'sweet'}}}
print(food_box.food.fruit.name)
apple

Link to Box.

7.1.2. decorator module: Write Shorter Python Decorators without Nested Functions

!pip install decorator

Have you ever wished to write a Python decorator with only one function instead of nested functions like below?

from time import time, sleep


def time_func_complex(func):
    def wrapper(*args, **kwargs):
        start_time = time()
        func(*args, **kwargs)
        end_time = time()
        print(
            f"""It takes {round(end_time - start_time, 3)} seconds to execute the function"""
        )

    return wrapper


@time_func_complex
def test_func_complex():
    sleep(1)


test_func_complex()
It takes 1.001 seconds to execute the function

If so, try decorator. In the code below, time_func_simple produces the exact same results as time_func_complex, but time_func_simple is easier and short to write.

from decorator import decorator


@decorator
def time_func_simple(func, *args, **kwargs):
    start_time = time()
    func(*args, **kwargs)
    end_time = time()
    print(
        f"""It takes {round(end_time - start_time, 3)} seconds to execute the function"""
    )


@time_func_simple
def test_func_simple():
    sleep(1)


test_func_simple()
It takes 1.001 seconds to execute the function

Check out other things the decorator library can do.

7.1.3. pydash.chunk: Split Elements in a List into Groups of n Items

!pip install pydash 
Collecting pydash
  Using cached pydash-5.0.2-py3-none-any.whl (84 kB)
Installing collected packages: pydash
Successfully installed pydash-5.0.2

If you want to split elements in a list into groups of n items, use pydash.chunk.

from pydash import py_

a = [1, 2, 3, 4, 5]
print(py_.chunk(a, 2))  # [[1, 2], [3, 4], [5]]
[[1, 2], [3, 4], [5]]

Link to pydash

Link to my article about pydash

7.1.4. Pipe: Use Inflix Notation in Python

!pip install pipe

Normally, you might use nested parentheses like below to combine multiple functions.

nums = [1, 2, 3, 4, 5, 6]
list(
    filter(lambda x: x % 2 == 0, 
            map(lambda x: x ** 2, nums)
          )
)
[4, 16, 36]

If you want to increase the readability of your code by using pipes, try the library pipe. Below is an example using this library.

from pipe import select, where
list(
    nums
    | select(lambda x: x ** 2)
    | where(lambda x: x % 2 == 0)
)
[4, 16, 36]

Link to my article on pipe.

Link to pipe.