Lädt...


🔧 My 5 Functions to QuickStart Functional Programming in Python


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

📚 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

And embracing function-based approaches, such as:

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!

⛓️

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

Example usage:

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():

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

Usage example:

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:

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:

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:


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:


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:

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!

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! 🎉👩‍💻👨‍💻

...

🔧 My 5 Functions to QuickStart Functional Programming in Python


📈 60.67 Punkte
🔧 Programmierung

🔧 5 Functions to QuickStart Functional Programming in Python


📈 60.67 Punkte
🔧 Programmierung

🔧 Introduction to Functional Programming in JavaScript: Partial functions #5


📈 33.92 Punkte
🔧 Programmierung

🔧 Introduction to Functional Programming in JavaScript: High order functions #3


📈 33.92 Punkte
🔧 Programmierung

🔧 Functional Programming for Beginners: Pure Functions Explained


📈 33.92 Punkte
🔧 Programmierung

📰 Programming Pioneer Grady Booch on Functional Programming, Web3, and Conscious Machines


📈 32.36 Punkte
📰 IT Security Nachrichten

🔧 Functions of Commercial Bank: Primary Functions and Secondary Functions


📈 31.52 Punkte
🔧 Programmierung

🔧 Functional Programming in Python: A New Way to Think About Problem-Solving


📈 29.37 Punkte
🔧 Programmierung

🔧 Functional and Non-Functional Testing.


📈 28.95 Punkte
🔧 Programmierung

🔧 DIFFERENCE BETWEEN FUNCTIONAL AND NON-FUNCTIONAL TESTING


📈 28.95 Punkte
🔧 Programmierung

🔧 Functional and Non functional testing


📈 28.95 Punkte
🔧 Programmierung

🔧 What is difference between functional and non functional testing ?


📈 28.95 Punkte
🔧 Programmierung

🔧 Functional and Non functional


📈 28.95 Punkte
🔧 Programmierung

🔧 Difference between Functional Testing and Non-Functional Testing with examples


📈 28.95 Punkte
🔧 Programmierung

🔧 Exploring the Depths of Functional and Non-Functional Testing


📈 28.95 Punkte
🔧 Programmierung

🔧 Exploring the Depths of Functional and Non-Functional Testing


📈 28.95 Punkte
🔧 Programmierung

🔧 Functional and Non-Functional Testing


📈 28.95 Punkte
🔧 Programmierung

🔧 Functional and Non-functional testing


📈 28.95 Punkte
🔧 Programmierung

🔧 Functional and Non-Functional Testing


📈 28.95 Punkte
🔧 Programmierung

🔧 Difference-Functional and Non-Functional Testing


📈 28.95 Punkte
🔧 Programmierung

🔧 FUNCTIONAL AND NON-FUNCTIONAL TESTING


📈 28.95 Punkte
🔧 Programmierung

🔧 Difference between Functional and Non Functional Testing


📈 28.95 Punkte
🔧 Programmierung

🔧 Difference between Functional Testing and Non Functional Testing with Examples


📈 28.95 Punkte
🔧 Programmierung

🔧 First-Class Functions, Higher-Order Functions, and Closures in Python – Explained with Code Examples


📈 26.97 Punkte
🔧 Programmierung

🔧 Durable functions in Python for Azure Functions | Azure Friday


📈 26.97 Punkte
🔧 Programmierung

🔧 Python for Beginners [1 of 44] Programming with Python | Python for Beginners


📈 26.8 Punkte
🔧 Programmierung

📰 Python QuickStart for People Learning AI


📈 26.75 Punkte
🔧 AI Nachrichten

📰 Python QuickStart for People Learning AI


📈 26.75 Punkte
🔧 AI Nachrichten

🔧 Embrace Functional Programming with /Dart 3.1/


📈 23.42 Punkte
🔧 Programmierung

matomo