One of the core features of modern programming languages is functions, but did you know Python has them too? Let’s take a look!
Table of Contents
- Concept Overview
- What’s the Difference Between a Function and a Method?
- How Do I Overload Functions?
- What Are args and kwargs?
- What Are Lambda Functions?
- Feeling Functional?
Concept Overview
Broadly, the purpose of a function is to group a section of code into a logical unit for reuse (a bunch of jargon, I know). For beginners, this is a tough concept to grasp because it often makes more sense to write code sequentially. For example, the following is pretty straightforward:
name = input("What is your name?") print(f"Hello, {name}! Nice to meet you.") color = input("What's your favorite color?") print(f"Oh, {color} is cool! Mine's purple.")
Why would you possibly want to add complexity to this code by introducing functions? I think that’s a valid critique. However, as programs get much longer, you’ll find yourself duplicating a lot of code. That’s when functions come in handy!
For example, in the sample above, we have a pattern of asking the user for some information and responding to it. If we find ourselves doing this a few more times, we might try to make a function to capture this repeated behavior:
def call_and_response(prompt: str, response: str): value = input(prompt) print(response % value)
Then, we can rewrite our sequence of statements as follows:
call_and_response("What is your name?", "Hello, %s! Nice to meet you.") call_and_response("What's your favorite color?", "Oh, %s is cool! Mine's purple.")
That’s really all there is to functions in Python. In the rest of this article, we’ll look at some questions you might have.
What’s the Difference Between a Function and a Method?
Chances are that you’ve heard terms like function, method, and procedure used interchangeably. The reason is that these terms all refer to the same thing: a chunk of code that can be reused.
With that said, there are purists who might argue that each term has a different meaning. For example, methods often refer to reusable chunks of code in object-oriented programming. Meanwhile, functions often refer to reusable chunks of code that return a value with no side effects (i.e., the chunk of code does not affect program state). As for procedures, you can think about them as the opposite of functions; chunks of code that do not return a value but instead alter program state.
Assuming the definitions above are satisfactory, here’s what each would look like in Python:
def procedure(): print("This is a procedure") def function(): return "This is a function" class Object: def method(): self.data = "This is a method"
How Do I Overload Functions?
Python doesn’t really have the concept of function or method overloading (i.e., the ability to have multiple methods with the same name but different parameters). Instead, we typically replicate the behavior of function overloading by providing a variety of optional parameters by setting defaults:
def overloaded(number: int=None, text: str=None): pass
In the example above, we could provide any combination of inputs. Optional parameters don’t exactly replicate the idea of function overloading, but they can be used to approximate the feature.
More recently, there appear to be some overloading features added to Python through “syntactic sugar,” but they’re really just adding a layer on top of optional parameters. See PEP 443 for the single dispatch feature and PEP 3124
for another proposed overloading feature.
What Are args and kwargs?
Great question! One of the weirder features of Python is the support for variable arguments (i.e., *args) and keyword arguments (i.e., **kwargs) in functions.
On one hand, variable arguments is a common feature in programming languages. The whole idea is to allow the user to provide an arbitrary amount of arguments that will be packaged up nicely for the developer as list of elements:
def variable_arguments(*args): print(args) variable_arguments("red", "green", "blue") # Prints ('red', 'green', 'blue')
On the other hand, keyword arguments is a feature I haven’t seen quite as often in other languages. However, the idea is still straightforward. Rather than relying on the position of the arguments, you can provide them by name. From the developer’s perspective, it’s as if you passed them a dictionary:
def keyword_arguments(**kwargs): print(kwargs) keyword_arguments(color="red", number=4, string="hello") # Prints {'color': 'red', 'number': 4, 'string': 'hello'}
What Are Lambda Functions?
Python has a feature which allows you to declare a function inline like you’re assigning a variable. This feature is often handy in situations where you want to store or pass around a function. A common example of this is sorting, which allows you to provide a function to specify the order of the elements:
nums = [5, 4, 6, 1, 2, 8] nums.sort() # [1, 2, 4, 5, 6, 8] nums.sort(key=lambda x: x % 2) # [2, 4, 6, 8, 1, 5] nums.sort(key=lambda x: 1 / x) # [8, 6, 5, 4, 2, 1]
This tends to be a little cleaner than defining the function outright and then passing the name of it inline.
Feeling Functional?
As you move away from long lists of statements, you’ll come to love functions. In fact, aside from reducing code duplication, they also make testing your code a lot easier! Maybe we’ll talk about that next time.
In the meantime, why not check out some of these related articles:
- Obfuscation Techniques: Shadowing Built-in Functions
- Can You Actually Return Multiple Values From a Function in Python?
- What If Python Only Had Functions
In addition, here are a few additional resources (#ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
Likewise, you can take your support even further by heading over to my list of ways to grow the site. Otherwise, thanks for checking this one out! We’ll see you next time.
Recent Code Posts
VS Code is a wonderful IDE that I use everyday. Sometimes though, little issues crop up that require you to customize your installation. Today, we'll talk about one of your options for customization:...
The tier list trope has been beaten to death by this point, but I couldn't help myself. I had to put together a script to generate one.