π 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!
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
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!
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)