The with
statement replaces former try...finally
blocks in Python. It ensures that clean-up code is executed. For example, it closes open files before leaving the block. Consider this code example (assuming this code is stored in a file named 'code.py'
):
with open('code.py') as code: print(code.read())
The output of this code would be the code itself (for nerds: a piece of code that generates itself is called a Quine):
''' OUTPUT with open('code.py') as code: print(code.read()) '''
No matter what goes wrong inside the with
block, Python will close the open file before moving on in the code. This way, you don’t need to enclose the code with a try...except
statement.
Single Expression ‘With’ Statement in One Line
Problem: Can you write the with
statement in a single line of code?
Solution: Yes, you can write the with
statement in a single line of code if the loop body consists only of one statement:
with open('code.py') as code: print(code.read())
In general, you can write any indentation block (like if
statements, with
environments, or while
loops) in a single line of code if the body consists of only one statement.
Exercise: The following interactive code throws an error if you run it. Fix the bug and run the correct code!
Multi Expression ‘With’ Statement in One Line
If the body consists of multiple statements, you can use a semicolon between the different statements:
with open('code.py') as code: print('The code:') print(code.read())
The previous code block becomes:
with open('code.py') as code: print('The code:'); print(code.read())
Note that in this particular instance, the semantics actually change because the code reads its own source file! But in all other cases, the semantics remain the same.
As soon as you have nested blocks like a for
loop inside a with
block, you cannot use this approach anymore because the code would become ambiguous. Believe it or not but the indentation serves a real purpose in Python! 😉
Nested Indentation Blocks in a One-Line ‘With’ Statement
If you know the Finxter tutorials, you also know that I seldomly conclude with such a statement “XYZ is impossible” because in most cases, it isn’t. If you’re in doubt whether you can compress an algorithm into a single line of code—don’t. You can compress all algorithms into a single line!
In most cases, you can avoid nested blocks by using list comprehension (rather than a for
loop) or the ternary operator (rather than an if
block).
Consider the following example with a for
loop inside a with
block:
with open('code.py') as code: for i in range(10): print(code.read())
Problem: One-Linerize a nested with block!
Wrong Solution: Write it into a single line:
Correct Solution: Replace the inner for loop with a list comprehension statement!
with open('code.py') as code: [print(code.read()) for i in range(10)]
While this code runs and solves the problem, please note that the chosen example does not make a lot of sense. The file is read only once—even if you place it into a for loop. The reason is that the file reader is done reading the file after the first iteration. In subsequent iterations it only reads the remaining characters (there aren’t any) so the output is not 10x only 1x the file contents.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.