You Can Do Really Cool Things With Functions In Python

ArjanCodes · Beginner ·🏗️ Systems Design & Architecture ·4y ago

Key Takeaways

The video demonstrates the use of functions in Python for designing a trading bot, including the implementation of trading strategies using the strategy pattern, closures, and partial function application, with tools such as functools and partial.

Full Transcript

the most common use of functions in a piece of code is to group operations and then call that function one or more times from another place in the code but functions are way more flexible than that in Python functions are objects of type cable you can Define type Al's for them you can pass functions as arguments to other functions if you use a package like fun tools you can even call functions partially it's better than sliced bread and I don't even like sliced bread have you noticed that in whatever country you are the people living there think that their bread is better than in any other country it's really weird I mean I live in the Netherlands so for us it doesn't really apply because our bread is actually better but if you live in one of those other countries you're basically living in a lie how do you cope with that another thing we're really good at in the Netherlands is writing software design guides for example this one Aron codes.com designu it's totally free it contains the seven steps that I take whenever I design a new piece of software from scratch I'm sharing it with you so I hope it helps you to avoid some of the mistakes that I made in the past and while you're at it order some Dutch bread or you know keep living in your bread fantasy world the choice is yours Aron codes.com designu and Link is also in description of this video today I'm going to show you a couple of not so common ways of using functions in your code as an example I'm going to use a trading system with different trading strategies so it's a bit like the strategy pattern but we're going to do some cool stuff with with functions let's dive into so there's a trading strategy protocol class here that has a should buy and a should cell method and both of these in the protocol they're not implemented so they raise a not implemented error if you scroll down you see that we have an average trading strategy that looks at the last few prices and then checks whether it's below or above the average and then decides whether or not to buy based on that number and then we also have a minmax trading strategy that looks at a minimum price and a maximum price if the price is below that minimum price then we should buy it if it's above a certain maximum price then we should start selling the asset that's the whole idea of these two strategies of course these strategies will never make you any money uh because the market is way more efficient than that so don't use this for real trading it's just meant as an example then we have a class trading bot that's a data class and it has an exchange and a trading strategy The Exchange is something that I just built myself very simple it has one constant with some price data so it doesn't actually connect to an exchange and we have a method for getting particular Market data that gets fake price data for us and then we have something that simulates buying and simulates selling so the trading board has an exchange and it has a trading strategy which is an instance of well one of these classes average or min max and then there is a run method that gets a symbol the type of currency that you want to buy or sell that method does a few things it gets the price data from the exchange it determines whether we should buy or sell and then it's going to buy or sell a certain quantity of that symbol and otherwise that's going to bring no action needed and then I simple main function that creates an exchange connects to exchange creates a trading strategy and then a trading bot and then runs it for Bitcoin my favorite cryptocurrency I actually bought some Bitcoin and ethereum again a while ago so Bitcoin ethereum to the Moon let's run this and see what happens so in this case it's going to sell 10 Satoshi probably in the Bitcoin US dollar market but I can also change now the trading strategy to something else for example let's use the average trading strategy and then what's going to happen is we're actually going to buy something so these strategies they have different effect on the behavior of the trading B which makes total sense right now this is a traditional implementation of the strategy pattern we have an abstract class or in this case a protocol class that defines the interface that has a method or in this case two method so it's not entirely traditional strategy pattern but it's pretty close then we have sub classes or classes that implement the protocol that have these two methods should buy and should sell and then there's another class that uses it so that's a traditional objectoriented approach of doing this and because it's objectoriented it relies heavily on classes if you're not too ATT that's to use in classes if you don't store State functions provide a great way to achieve the same effect as the strategy pattern in this example in general functions can replace or significantly simplify code that uses classes and objectoriented design patterns that doesn't mean that design patterns aren't needed anymore they're still useful but in many cases a functional approach might actually be much simpler so let's change this code to use functions instead of classes basically if you look at the signature of these methods each of them gets a bunch of prices and then returns a Boolean value so in order to transform this example into using a more functional approach instead of all these classes we should perhaps Define this function type before we start doing that job so what I'm going to do is create a trading strategy function which is going to be our function type and that's going to be a cable and the input is going to be the list of prices that's a list of integers and what it's going to return is a Boolean value so this is basically what any of the trading strategy functions are going to look like so this class I'm going to delete because we're not going to use the class anymore and then we have our average trading strategy functions and we have the minmax trading strategy functions and we should simply transform them into functions that follow this signature so let me also remove this class definition because we don't need that anymore and I'm going to take these lines here and let's de indent them I'll remove the self and the same thing here so remove the self so we have should buy and should sell and then let's also change the name so that we know that this is the average strategy so this is should buy average and we have should sell average and we can do the same thing for the minmax trading strategy so I'll just take again these function definitions remove the self like so and then we're going to call this minmax instead like so so now we have our functions and now we need to change the trading bot class because it no longer has a trading strategy but it has a buy function and a sell strategy function so let's call that the buy strategy which is a trading strategy function and we have the self strategy which is also a trading strategy function and in the Run methods we don't do this but we call here the buy strategy and here we call the sell strategy like so and now we can create the trading strategy here we can delete these lines and we simply provide the functions that the trading bot needs right here so let's say we could have the should buy average and should sell average like so and now let's run this code just to verify that this still works so there is a problem here function object has no attribute should buy and that's of course because we don't need to do the call here anymore because this is already a function so let's remove that as well let's run this one more time and now we're getting exactly the same but because we're using the more functional approach now it's the code has become a bit shorter because we don't have all these classes everywhere and another Advantage is that in the trading bot we can now Supply different combinations of functions so we could have a buy strategy for average and we could have a sell strategy which is minmax and then let me run this one more time and well the result is the same but you can imagine that we can make now any combination that we like so like so and then let's see what happens then and now there is no action needed so by using more functional approach here we've also introduced some extra flexibility now of course you could also do this with the regular strategy pattern in a sense that instead of having a trading strategy that has both a should buy and should sell method we could create classes for buying and for selling leading to even more classes and subclasses by the way so personally I really prefer this type of approach where we're dealing with simple functions that we just pass to the training bot in fact even the trading Bots we could turn it into a function because at the moment it's a simple it's a single method we could actually turn this into a simple function that gets a symbol an exchange a buy strategy and a sell strategy and then just runs the strategy and there is no class needed anymore but for now I'll leave it like it is it's also not a big issue that it's a class and we might want to add more methods to it in the future one of the issues with the functional version of the strategy pattern that we use that there is no way to pass param to these functions and that's because trading B expects these functions to have a particular type it expects these functions to accept a list of prices but what if for the average trading strategy you want to pass parameters like the window size or for the min max trading strategy we want to set the minimum and maximum price currently we can't do that in the original version of the coded use classes you could pass these parameters to the class initializer and then store them as state with functions there are other ways to fix this one of them is by using closures so let's see how that works what we're going to do is create a function that returns a trading strategy function and then we can pass parameters to that particular function and then it can pass those parameters to the closure that it creates and then it returns a function that we can still use in the trading strategy so for example here we have should buy average and we might want to change the window size here currently it's three we might want want to make it bigger or smaller so what we can do instead is use a closure let's call that should buy average closure and that's going to get a window size which is an integer and what this is going to return is a trading strategy function and then we Define the should buy average function inside of this closure function and here the minus three we're setting that to the window size like so and now what we're going to do is return should buy average so that's our closure function and because we're passing the window size as a parameter here we can use it in should buy average that's the whole idea of the closure but the function that we return is still a function that only gets a list of prices so this is the closure mechanism what you can now do in the main function is that instead of passing this function directly we can pass a should buy average closure and then we actually pass it the window size so for example I could now pass the window size of four and this is going to return us the average function that takes a window size of four and now let's run this and well apparently we still need to buy more Bitcoin so this is what a closure does and you can basically use the closure for any of these other functions as well so for example Force should sell minmax it's probably useful if we have a closure that allows to Define what the price is so let's create that should sell min max closure so this is going to get a Max price which is an INT and this is also going to return a trading strategy function and then this function here is going to be a part of the closure and instead of having this fixed price I'm going to replace it by the max price and then it's going to return the function as a result like so and this line doesn't make any sense anymore so now we have this should sell minmax closure and then I can go here should sell minmax closure and I provide a price let's say I only want to sell if the price is above 35,000 like so and I need to put two additional zeros this is by the way a nice way in Python to uh make bigger numbers more clear here in the interface actually does nothing it doesn't change the value of this number but it makes it a bit clear what how many zeros there are and what it exactly means so that's why I'm using that here so should buy and should sell now use a closure so we can set some parameters here and trading bot still doesn't know anything about that because it simply gets a trading strategy function from it so let's run this and now we're still buying 10 uh cryptocurrencies if I change the window here to something else let's see now I'm not buying anything because the window has changed and apparently we're just on the limit of whether we should buy or not using closure solve the problem of not being able to pass parameters to these functions but it's a bit for both and it's not very flexible instead a more elegant way of solving this is by using partial functions a partial application or partial function application fixes a number of arguments in the original function and returns a new function with about those arguments this is different from currying by the way which is not a term you might have heard from the functional programming domain currying means that you transform a function that takes multiple arguments into a sequence of functions that each take only a single argument and because you can Curry any function this is very useful in theoretical computer science for example where you want to study functions with multiple arguments and then you can transform them into a simple theoretical model of functions taking only a single argument partial functions are way more practical approach and in this case they can really help to simplify the code and make it way more flexible so let's see how that works so let's first import partial from fun tools because that's what we're going to use to make these functions a bit more flexible and what I'm going to do now is really simplify these functions right here so instead of making this a closure what I'll do is simply add the parameter to the should bu average function instead and then I'll delete this line I'll delete this line and this we're going to De indent so now I have a simple should buy average function and for should sell I can also add the window size in exactly the same way so now should cell also expects a window size for should bu I'm doing exactly the same thing so here I'm going to provide a minimum price like so and should cell is exactly the same so I'm also going to add here a maximum price which is an INT and then I'll delete the closure here and I'll de inent this and now we have our four functions back and these functions are still very simple they just have a bunch of extra parameters this does mean that now we can directly use use them in the trading agent because this expects a should buy and a should sell method that follow exactly the trading strategy function type which expects a list of prices and returns a Boolean and now these functions they don't adhere to this type anymore because well they expect other things as well such as this window size or the minimum and maximum price now you could get away with it in this particular example by supplying default values here and then you could still use them directly but then it would still be impossible to basically set it to a different value than the default value and we actually want to change these things so um we need a better solution and partial can really help here so what we can do with partial is create partially applied versions of these particular functions so what you can do is and that's actually really neat we can create a buy strategy which is then a partial application so I'm using partial here of the function which is let's say should buy average and we're going to supply the argument so we're going to supply a window size of four and now what's interesting is that we get back from partial another function like the closure but with the window size of four so now we can pass to the trading Bots the by strategy function like so and as you see the type errors are gone because well buy strategy is actually a function that returns a Boolean and that takes a list of prices and similarly we can create a sell strategy which is also partial application of let's say should sell average or let's do the uh theand Max actually and then we're going to supply a Max price of let's say $35,000 like so and now what I can do here is Supply the self strategy and let's run this see what happens so we get some missing parenthesis somewhere oh I think this one doesn't need to be there let's run that again and now we're back at a working state of the code again so this is really powerful because now it means that we have flexibility in the way that we Define our functions we can supply these extra arguments here maximum minimum price window sizes Etc but because of partial we can transform these functions into new functions with partially applied arguments so this is actually the should buy average function except it already gets a window size of four we've partially applied the function and this is really neat because this is way shorter than using the closure solution that I showed you before and it also allows you to create these functions a bit more independently of the type that's something like the uh Trading B expects because uh you can simply use partial application to resolve the rest of the arguments and then the trading bot doesn't have to know anything about that so I think this a really neat way of allowing for more flexibility in your code while still keeping things relatively simple so partial function application I love it I think you should also experiment with it a bit more in your code if you have used partial functions already let me know in the comments what your thoughts are about this so anyway I hope you enjoyed this this video and that it gave you some ideas of how you could use partial function application to your advantage give the video a like if you enjoyed it consider subscribing to my channel if you want to learn more about software design and development thanks for watching take care and see you soon

Original Description

💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide. Here are a few not-so-common things you can do with functions in Python, including closures and partial function application. Functions are incredibly powerful and you can use them to write code that's really clean and often a lot shorter than when relying on classes and object-oriented programming. The code I worked on in this video is available here: https://github.com/ArjanCodes/2022-functions. 🎓 ArjanCodes Courses: https://www.arjancodes.com/courses. 💬 Join my Discord server: https://discord.arjan.codes. ⌨️ Keyboard I’m using: https://amzn.to/49YM97v. 🔖 Chapters: 0:00 Intro 1:32 Explaining the code example 3:56 About the Strategy pattern 4:29 Replacing the class structure by functions 9:24 Passing extra parameters using closures 13:37 Using partial functions #arjancodes #softwaredesign #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from ArjanCodes · ArjanCodes · 47 of 60

1 Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
ArjanCodes
2 FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
ArjanCodes
3 Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
ArjanCodes
4 Build a GLASSMORPHISM React Component - Typescript & Material-UI
Build a GLASSMORPHISM React Component - Typescript & Material-UI
ArjanCodes
5 Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful 🚀
Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful 🚀
ArjanCodes
6 100% CODE COVERAGE - Think You're Done? Think AGAIN.☝
100% CODE COVERAGE - Think You're Done? Think AGAIN.☝
ArjanCodes
7 Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
ArjanCodes
8 1000 Subscribers! 🚀 WHY I Started this Channel and WHAT'S NEXT
1000 Subscribers! 🚀 WHY I Started this Channel and WHAT'S NEXT
ArjanCodes
9 Channel Trailer ArjanCodes - March 2021
Channel Trailer ArjanCodes - March 2021
ArjanCodes
10 Exception Handling Tips in Python ⚠ Write Better Python Code Part 7
Exception Handling Tips in Python ⚠ Write Better Python Code Part 7
ArjanCodes
11 Monadic Error Handling in Python ⚠ Write Better Python Code Part 7B
Monadic Error Handling in Python ⚠ Write Better Python Code Part 7B
ArjanCodes
12 GW BASIC Games I Wrote When I Was a Kid 🎮 Running 30 Year Old Code
GW BASIC Games I Wrote When I Was a Kid 🎮 Running 30 Year Old Code
ArjanCodes
13 Why You Should Think About SOFTWARE ARCHITECTURE in Python 💡
Why You Should Think About SOFTWARE ARCHITECTURE in Python 💡
ArjanCodes
14 Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
ArjanCodes
15 QUESTIONABLE Object Creation Patterns in Python 🤔
QUESTIONABLE Object Creation Patterns in Python 🤔
ArjanCodes
16 If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
ArjanCodes
17 CODE ROAST: Yahtzee - New Python Code Refactoring Series!
CODE ROAST: Yahtzee - New Python Code Refactoring Series!
ArjanCodes
18 7 UX Design Tips for Developers
7 UX Design Tips for Developers
ArjanCodes
19 Going All-in on Software Design in Python + an ANNOUNCEMENT 🎙
Going All-in on Software Design in Python + an ANNOUNCEMENT 🎙
ArjanCodes
20 🎙 Interview with Sybren Stüvel, Developer @ Blender 3D
🎙 Interview with Sybren Stüvel, Developer @ Blender 3D
ArjanCodes
21 Do We Still Need Dataclasses? // PYDANTIC Tutorial
Do We Still Need Dataclasses? // PYDANTIC Tutorial
ArjanCodes
22 7 Python Mistakes That Instantly Expose Junior Developers
7 Python Mistakes That Instantly Expose Junior Developers
ArjanCodes
23 Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
ArjanCodes
24 GitHub Copilot 🤖 The Future of Software Development?
GitHub Copilot 🤖 The Future of Software Development?
ArjanCodes
25 More Python Code Smells: Avoid These 7 Smelly Snags
More Python Code Smells: Avoid These 7 Smelly Snags
ArjanCodes
26 Test-Driven Development In Python // The Power of Red-Green-Refactor
Test-Driven Development In Python // The Power of Red-Green-Refactor
ArjanCodes
27 5 Tips To Keep Technical Debt Under Control
5 Tips To Keep Technical Debt Under Control
ArjanCodes
28 Refactoring A Tower Defense Game In Python // CODE ROAST
Refactoring A Tower Defense Game In Python // CODE ROAST
ArjanCodes
29 The Factory Design Pattern is Obsolete in Python
The Factory Design Pattern is Obsolete in Python
ArjanCodes
30 Why the Plugin Architecture Gives You CRAZY Flexibility
Why the Plugin Architecture Gives You CRAZY Flexibility
ArjanCodes
31 Refactoring A Data Science Project Part 1 - Abstraction and Composition
Refactoring A Data Science Project Part 1 - Abstraction and Composition
ArjanCodes
32 Refactoring A Data Science Project Part 2 - The Information Expert
Refactoring A Data Science Project Part 2 - The Information Expert
ArjanCodes
33 Refactoring A Data Science Project Part 3 - Configuration Cleanup
Refactoring A Data Science Project Part 3 - Configuration Cleanup
ArjanCodes
34 Purge These 7 Code Smells From Your Python Code
Purge These 7 Code Smells From Your Python Code
ArjanCodes
35 Running A Software Development YouTube Channel
Running A Software Development YouTube Channel
ArjanCodes
36 Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
ArjanCodes
37 Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
ArjanCodes
38 How To Easily Do Asynchronous Programming With Asyncio In Python
How To Easily Do Asynchronous Programming With Asyncio In Python
ArjanCodes
39 The Software Designer Mindset
The Software Designer Mindset
ArjanCodes
40 NEVER Worry About Data Science Projects Configs Again
NEVER Worry About Data Science Projects Configs Again
ArjanCodes
41 Powerful VSCode Tips And Tricks For Python Development And Design
Powerful VSCode Tips And Tricks For Python Development And Design
ArjanCodes
42 8 Python Coding Tips - From The Google Python Style Guide
8 Python Coding Tips - From The Google Python Style Guide
ArjanCodes
43 What Is Encapsulation And Information Hiding?
What Is Encapsulation And Information Hiding?
ArjanCodes
44 8 Tips For Becoming A Senior Developer
8 Tips For Becoming A Senior Developer
ArjanCodes
45 Building A Custom Context Manager In Python: A Closer Look
Building A Custom Context Manager In Python: A Closer Look
ArjanCodes
46 GraphQL vs REST: What's The Difference And When To Use Which?
GraphQL vs REST: What's The Difference And When To Use Which?
ArjanCodes
You Can Do Really Cool Things With Functions In Python
You Can Do Really Cool Things With Functions In Python
ArjanCodes
48 Announcing The Black VS Code Theme (Launching April 1st)
Announcing The Black VS Code Theme (Launching April 1st)
ArjanCodes
49 7 DevOps Best Practices For Launching A SaaS Platform
7 DevOps Best Practices For Launching A SaaS Platform
ArjanCodes
50 Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
ArjanCodes
51 Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
ArjanCodes
52 Things Are Going To Change Around Here
Things Are Going To Change Around Here
ArjanCodes
53 Dependency Injection Explained In One Minute // Python Tips
Dependency Injection Explained In One Minute // Python Tips
ArjanCodes
54 How To Setup A MacBook Pro M1 For Software Development
How To Setup A MacBook Pro M1 For Software Development
ArjanCodes
55 A Simple & Effective Way To Improve Python Class Performance
A Simple & Effective Way To Improve Python Class Performance
ArjanCodes
56 How To Write Unit Tests For Existing Python Code // Part 1 of 2
How To Write Unit Tests For Existing Python Code // Part 1 of 2
ArjanCodes
57 How To Write Unit Tests For Existing Python Code // Part 2 of 2
How To Write Unit Tests For Existing Python Code // Part 2 of 2
ArjanCodes
58 Make Sure You Choose The Right Data Structure // Python Tips
Make Sure You Choose The Right Data Structure // Python Tips
ArjanCodes
59 5 Tips For Object-Oriented Programming Done Well - In Python
5 Tips For Object-Oriented Programming Done Well - In Python
ArjanCodes
60 Next-Level Concurrent Programming In Python With Asyncio
Next-Level Concurrent Programming In Python With Asyncio
ArjanCodes

This video teaches how to use functions in Python to design a trading bot, including the implementation of trading strategies using the strategy pattern, closures, and partial function application. It demonstrates how to create a trading bot with an exchange and a trading strategy, and how to use partial function application to create flexible functions.

Key Takeaways
  1. Define a trading strategy protocol class
  2. Implement average and minmax trading strategies
  3. Create a trading bot with an exchange and a trading strategy
  4. Run the trading bot for Bitcoin using the average trading strategy
  5. Use closures to create functions that take a list of prices as input
  6. Use partial functions to simplify code and make it more flexible
  7. Supply extra arguments to functions using partial function application
  8. Resolve the rest of the arguments for a function using partial function application
💡 Partial function application can be used to create flexible functions that can be used independently of the type expected by a trading bot.

Related Reads

📰
System Design Was Hard Until I Learned These 50 Concepts [2026 Edition]
Learn 50 essential system design concepts to improve scalability, reliability, and security, and ace your interviews
Medium · AI
📰
Rust Went Mainstream While You Were Arguing About JavaScript Frameworks
Rust has gained mainstream traction while developers were distracted by JavaScript framework debates, highlighting its growing importance in the programming landscape
Medium · Programming
📰
FULL STACK Developer
Learn the basics of full stack development and its importance in the tech industry
Dev.to · Parthipan M
📰
Workflow Series (10): Enterprise Architecture — Registry, Composition, and Governance
Learn to manage multiple workflows with enterprise architecture principles, including registry, composition, and governance, to scale your workflow systems efficiently
Dev.to · WonderLab

Chapters (6)

Intro
1:32 Explaining the code example
3:56 About the Strategy pattern
4:29 Replacing the class structure by functions
9:24 Passing extra parameters using closures
13:37 Using partial functions
Up next
How to Forward Device Data Via HTTP/MQTT/Modbus/BACnet in EG71
Milesight IoT
Watch →