My 5 Functions to QuickStart Functional Programming in Python
Tags: programming, beginners, tutorial, python
Published: 2023-12-05 17:43:22

> _📚 I was inspired by 🦄 [The Unicorn Project](https://www.amazon.com/Unicorn-Project-Developers-Disruption-Thriving), 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:

```python
x = 100
x = x + 10
```

And embracing function-based approaches, such as:

```python
add_ten = lambda x: x + 10
x       = add_ten(100)
```

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](https://github.com/webcrumbs-community/webcrumbs) 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!

{% cta https://github.com/webcrumbs-community/webcrumbs %}⭐️ Give WebCrumbs a Star! ⭐️ {% endcta %}

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:

```python
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
```

Example usage:

```python
run(print, len)('webcrumbs.org') # prints 13
```

---

# 🖨️
## 2. Print function

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

```python
def echo(content):
    print(content)
    return content
```

Usage example:

```python
run(len, echo, len)('webcrumbs.org') # prints 13 and returns 2, since 13 has 2 characters
```

---

# 🔁
## 3. Loop function

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

```python
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
```

Usage example:

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

# shows a processing bar
# 100.00% :::::::::::::::::::: |  2 / 2 |:  Example
# prints 3 then 6
```

---

# 📦
## 4. Download functions

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

```python

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
```

Usage example:

```python

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
```

---

# ✂️
## 5. Small lists function

To process large lists in manageable chunks, use this:

```python
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
```

--- 

## Share Your Functional Programming Gems!

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

{% cta https://github.com/webcrumbs-community/webcrumbs %} Explore more on our GitHub! {% endcta %}

{% cta https://webcrumbs.org %} Dive into the world of WebCrumbs! {% endcta %}

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](https://github.com/webcrumbs-community/webcrumbs) or [WebCrumbs](https://webcrumbs.org) for more insights and tools. 

Happy coding! 🎉👩‍💻👨‍💻