🔧 5 Functions to QuickStart Functional Programming in Python
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
So, you may have already heard about functional programming, i.e., writing code that avoids mutable state and emphasizes the use of pure functions.
In python, it means don't:
x = 100
x = x + 10
And do instead:
add_ten = lambda x: x + 10
x = add_ten(100)
🦄 The Unicorn Project
I started giving it a chance after I read The Unicorn Project. It is an entertaining book about Maxime, a developer who loves functional programming because she knows that pure functions and composability are better tools to think with.
Knowing the theory is good, but knowing the practice is key.
I am sure there are many ways of using functional programming in Python. Here is the way I do it and you'll see it's very peculiar. (Share your way below too!)
⛓️
1. Chain function
I like writing a chain function that I usually call run()
. It returns a function that combines other functions.
Why? For simplicity, let's say you want to get the length of a string and then print it. (It gets nicer when you start using your own functions, though)
You could do print(len('webcrumbs.org'))
, but in real world scenarios eventually you'll see yourself wrapping so many elements that it gets confusing.
Creating a chain function will help you with readability.
Here's an example of a chain function I use:
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
Use it like:
run(print, len)('webcrumbs.org') # prints 13
🖨️
2. Print function
There's one problem with the print()
, though, which is, you cannot continue chaining other functions after that because it returns None.
To solve it, I like creating my own print function, which I call echo()
just to differentiate from the native one.
def echo(content):
print(content)
return content
Use it like this:
run(len, echo, len)('webcrumbs.org') # prints 13 and returns 2, since 13 has 2 characters
🔁
3. Loop function
Okay. But what if you are not just printing the length of a string, but you want to apply a process to a list of strings?
You could do [run(print, len)(item) for item in ['web', 'crumbs'])
. But it's not very readable.
I usually create a loop function that helps me with that.
It also helps me being time efficient because I can use more advanced loops such as threading. And I made it pretty! Using the atpbar
library, it shows a nice processing bar as a plus.
Here's an example with mantichora (but you can write with the threading tool you prefer):
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
Use it like this:
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
There are many other functions that I use in many different projects. One that is useful is a function to download code or files.
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
Now you can use it like this:
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
But let's say your list is too big and you want to have it processed in small chunks.
You can make a list of small lists the size you want with this function:
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
Do you have any functions like these that you use in many projects? Would like me to share more functions I use? Let me know below!
...
🔧 Functional and Non-Functional Testing
📈 28.61 Punkte
🔧 Programmierung
🔧 Functional and Non-functional testing
📈 28.61 Punkte
🔧 Programmierung
🔧 Functional and Non-Functional Testing
📈 28.61 Punkte
🔧 Programmierung
🔧 FUNCTIONAL AND NON-FUNCTIONAL TESTING
📈 28.61 Punkte
🔧 Programmierung
🔧 Functional and Non-Functional Testing.
📈 28.61 Punkte
🔧 Programmierung
🔧 Functional and Non functional testing
📈 28.61 Punkte
🔧 Programmierung
🔧 Functional and Non functional
📈 28.61 Punkte
🔧 Programmierung
📰 Python QuickStart for People Learning AI
📈 26.67 Punkte
🔧 AI Nachrichten
📰 Python QuickStart for People Learning AI
📈 26.67 Punkte
🔧 AI Nachrichten