Leveraging Python's Implicit "return None" Statements
Key Takeaways
The video discusses Python's implicit return None statements and how to leverage them to write cleaner code, providing examples and tips for better coding practices.
Full Transcript
hey folks it's Dan Bader and today I want to talk about implicit return statements in Python Python automatically adds implicit return statements to the end of any function that you write so therefore if a function does not specify return value it will return none by default and I know this can be a little bit confusing so with this video tutorial you're gonna learn exactly how these implicit return statements work and how you can use them to your advantage and then of course also how are you gonna be able to see how they work in other people's code which is really important for understanding the Python code that's out there okay so let's start with a simple example I've got this dummy function here and it just contains a simple if statement here and we can see here in the last line it actually returns none and now with the implicit returns feature in Python you can simplify this function so let me show you a new version off this function that will be exactly equivalent so it would lead to the same output but it doesn't actually return none here it's just a bear return statement and a bear return statement in Python implies that none will be returned you might use that in some cases to simplify your code a little bit could also be confusing is if someone doesn't know about this feature so it's always something to keep in mind now because the return statement is implicit that means you can actually leave it out completely so that's what I'm doing here in this foo 3 function in this case I'm leaving out the return statement in the else part of that if statement and this will lead to exactly the same result so all these functions are exactly equivalent they have the exact same return values but you can see here that this last option is quite a bit shorter and easier to read than the first one but just to confirm that they actually all have the same output let's actually run them so what I'm gonna do here is I'm gonna go through each of those functions and I'm call I'm gonna call them with an argument of false which is going to trigger the else branch in the the central if statement here and we should we should expect to always get a none return value here so stride with the fool one function just kind of the unchanged version of that function the original version of that function so alright so this returned none now let's try it with the bear return statement that would also imply return none and again this returns none as well and now let's try it with the third function or foo 3 function here that doesn't include the else branch altogether it only has the kind of the truthy branch here and there's no return statement whatsoever so once I run this you can see here it also returns none and if I pass a truthy argument you can see here that it correctly returns the actual value so you know if I pass something else it'll just bounce that back to me and yeah I guess this is proof that this really works and I'm not just making this stuff up now of course the question that remains is when should you actually use this when is it a good idea to use this feature in your own Python code so my rule of thumb is if a function does not have a return value so in other languages that would be called a procedure then I always leave out the return statement so I don't add empty return statements if I don't have any sensible value to return right so for example if I wrote something like the built-in print function that would only ever be called for its side-effects would never return anything then I wouldn't put a return statement there it just wouldn't make any sense in my mind if you're following that principle the only time you need to decide whether or not to use a implicit return nun statement is when a function actually has a return value that makes sense from a logical perspective right so the print function we're only calling it for its side-effects but the sum function for example we want to call that because we expect some kind of return value with a function like that where it would logically make sense for it to return none I think that's where we need to discuss whether or not you should use an implicit or an explicit return on statement I think on the one hand you could say that well if you leave out the return on statement it makes the code more concise and therefore easier to read and understand and maybe you could say makes it prettier on the other hand this feature might really surprise some programmers and it they might not know that Python behaves that way when it comes to writing clean and maintainable code then using the surprising behavior is usually not the best way to go about it so for example the book that I'm working on I had a couple of code examples there or I think I had one code example there that was using an implicit return none statement and so I started getting these regular emails where people mentioned that hey then you're missing a return statement here and I have this almost like this you know template saved the way that would that I would send people as a reply was like hey you know what Python actually does these implicit return statements and that's totally ok but I can see why it's confusing and so my thinking there has shifted a bit where I'm thinking you know in this case and the book I actually changed it because the point of that code example wasn't about the missing return statement or being concise but it was more about something else entirely and being very clear and making the the example very easy to understand so in this case I think it made sense to bring back the explicit return statement I mean don't get me wrong right I love writing clean and beautiful code as much as anyone else and I used to feel really strongly that programmers should really know the ins and outs of the language they're working with but also you got to be you got to be realistic about this stuff right so when you consider the maintenance impact of even a simple misunderstanding where it's you know you're working in a in a bigger team and there's this back and forth on oh hey are missing a return statement here no I guess there's this like rule in Python that you can leave it out and then you know someone is asking about that in chat or maybe someone is tapping on the shoulder so that caused an interruption and it just you know it's it's like the butterfly effect where you have this little thing and it just kind of spirals out of control it has a much larger impact than you would have thought it would have initially and so I think when you consider the maintenance impact of stuff like that then I would be leaning more towards making the code explicit and very clear so I'm not gonna make a definite recommendation here right or like a definitive recommendation we're gonna say hey you always have to use this feature you you should never use this feature but it always depends so honestly it really depends on the circumstances but personally I try to keep in mind that code is communication and it is meant for primarily for humans not for computers otherwise we would all be writing sort of some kind of binary you know bytecode assembler language there's something like that or I wouldn't be writing Python so I always try to err on the side of being more explicit so that people have an easier time understanding and maintaining my code so you know that might not be your philosophy but I think it it really helps in making it easier to work with other people and also making your programs more maintainable in the long run all right I know I'm kind of leaving you alone here making this decision but but try it out be aware that this exists and implicit returned values are a thing in Python they're gonna come in handy and they're you're going to encounter them but also balance it with the need for being clear and writing maintainable code and actually if your philosophy when it comes to writing clean code aligns with mine and what I just described then check out my book because there are many more examples just like the one I just discussed and I'm always trying to approach it from the angle that I just explained you know where I believe that code is communication it's written for humans primarily we've got to make sure that we're writing explicit and clear code so if this is something that you're interested in learning or interested in you know improving your skills in that and kind of picking up that mindset then check out my book Python tricks I think you're gonna enjoy it alright thanks so much for listening and happy Python II [Music]
Original Description
https://dbader.org/python-tricks ► Write better and cleaner Python code with these bite-sized examples and tips
Python adds an implicit "return None" statement to the end of any function. Therefore, if a function doesn't specify a return value it returns None by default.
This means you can replace return None statements with bare return statements or even leave them out completely and still get the same behavior in your programs.
In this video tutorial I show you the rundown of how implicit return statements work in Python and how you can use them to make your code cleaner and more Pythonic.
I also cover the potential downsides of using this feature and how it can make your code *harder* to read in some cases.
On the one hand, you could argue that omitting an explicit return None statement makes the code more concise and therefore easier to read and understand. Subjectively you might also say it makes the code "prettier."
On the other hand, it might surprise some programmers that Python behaves this way. When it comes to writing clean and maintainable code, surprising behavior is rarely a good sign.
Watch the video for the full discussion.
FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery
SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube
* * *
► Python Developer MUGS, T-SHIRTS & MORE: https://nerdlettering.com
FREE Python Tutorials & News:
» Python Tutorials: https://dbader.org
» Python News on Twitter: https://twitter.com/@dbader_org
» Weekly Tips for Pythonistas: https://dbader.org/newsletter
» Subscribe to this channel: https://dbader.org/youtube
Playlist
Uploads from Real Python · Real Python · 49 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
▶
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Python for Data
View skill →
🎓
Tutor Explanation
DeepCamp AI