DEV Community

Cover image for My 5 Functions to QuickStart Functional Programming in Python
OpenSource
OpenSource

Posted on • Updated on

My 5 Functions to QuickStart Functional Programming in Python

πŸ“š I was inspired by πŸ¦„ The Unicorn Project, a captivating story about Maxime, a developer who champions functional programming.

Have you explored functional programming in Python? It's about writing code that avoids mutable state and emphasizes pure functions. In Python, this means moving away from direct variable modifications, like:

x = 100
x = x + 10
Enter fullscreen mode Exit fullscreen mode

And embracing function-based approaches, such as:

add_ten = lambda x: x + 10
x       = add_ten(100)
Enter fullscreen mode Exit fullscreen mode

Knowing the theory is great, but practical application is key. Here’s my unique take on functional programming in Python, and I’m eager to hear about yours too!


Support us! πŸ™β­οΈ

By the way, I'm part of the WebCrumbs team, and it would mean a lot if you could check out our no-code solution for Node.js that simplifies web development. Giving us a star would be fantastic.

We're putting in a ton of effort to help devs take their ideas to a live website as quickly and easily as possible (think: effortless plugin and theme integration), and every bit of support is truly appreciated!

⭐️ Give WebCrumbs a Star! ⭐️

Ok. Now, let's dive into some cool functions I use to start with functional programming in Python.


⛓️

1. Chain function

I often use a run() function to combine other functions, enhancing readability, especially when dealing with complex operations. Here's how I define it:

def run(*tasks):
    def compiled_tasks(*args):
        result = None
        for task in tasks:
            if not callable(task):
                raise('Cannot compile. Argument is not a function.')
            if not result:
                result = task(*args)
                continue
            result = task(result)
        return result
    return compiled_tasks
Enter fullscreen mode Exit fullscreen mode

Example usage:

run(print, len)('webcrumbs.org') # prints 13
Enter fullscreen mode Exit fullscreen mode

πŸ–¨οΈ

2. Print function

The native print() returns None, breaking the function chain. To overcome this, I use echo():

def echo(content):
    print(content)
    return content
Enter fullscreen mode Exit fullscreen mode

Usage example:

run(len, echo, len)('webcrumbs.org') # prints 13 and returns 2, since 13 has 2 characters
Enter fullscreen mode Exit fullscreen mode

πŸ”

3. Loop function

For processing lists, I use a loop function, incorporating threading for efficiency and atpbar for a visual touch:

def for_item_in(_list, **kwargs):
    name = kwargs.get('name', _list)
    mode = kwargs.get('mode', 'threading')
    silent = kwargs.get('silent', None)
    if mode == 'threading':
        def inner_function(do):
            with mantichora(mode='threading') as mcore:
                for item in _list:
                    mcore.run(do, item)
                if silent:
                    for item in _list:
                        mcore.receive_one()
                else:
                    for item in atpbar(_list, name=name):
                        mcore.receive_one()
                return mcore.returns()
    else:
        def inner_function(do):
            if silent:
                for item in _list:
                    do(item)
            else:
                for item in atpbar(_list, name=name):
                    do(item)
    return inner_function
Enter fullscreen mode Exit fullscreen mode

Usage example:

for_item_in(['web', 'crumbs'], name='Example')(run(print, len))

# shows a processing bar
# 100.00% :::::::::::::::::::: |  2 / 2 |:  Example
# prints 3 then 6
Enter fullscreen mode Exit fullscreen mode

πŸ“¦

4. Download functions

For downloading files or code, here’s a handy function:


download = lambda url: requests.get(url).text.replace('\n', '').replace('\r', '')

def download_file(url):
    ext = url.split('.')[-1]
    local_path = f"{TMP_FOLDER}/{str(int(datetime.timestamp(datetime.now()) * 1000000))}.{ext}"
    with open(local_path, 'wb') as f:
        for chunk in requests.get(url,stream=True).iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    return local_path
Enter fullscreen mode Exit fullscreen mode

Usage example:


run(
  echo,
  download_file
)([
  'https://link-to-a-file',
  'https://link-to-another-file'
])
# shows a processing bar
# 100.00% :::::::::::::::::::: |  2 / 2 |:  Example
# download files and prints their local paths
Enter fullscreen mode Exit fullscreen mode

βœ‚οΈ

5. Small lists function

To process large lists in manageable chunks, use this:

def small_list(large_list, size):
    out = []
    last = 0
    while last < len(large_list):
        out.append(large_list[int(last):int(last+size)])
        last += size
    return out
Enter fullscreen mode Exit fullscreen mode

Share Your Functional Programming Gems!

Do you have favorite functions for your projects? Want to see more of mine? Let’s discuss below!

Explore more on our GitHub!

Dive into the world of WebCrumbs!

Congratulations on completing this read! By embracing these functional programming techniques, you're well on your way to cleaner, more efficient Python code. Next step? Head over to our GitHub or WebCrumbs for more insights and tools.

Happy coding! πŸŽ‰πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Top comments (0)